2016-05-09 25 views
0

我想与Java,JSch库和Ubuntu操作系统的终端来打开ssh,但有错误这样的SSH服务器上:运行SSH使用Java

Pseudo-terminal will not be allocated because stdin is not a terminal. 
Permission denied, please try again. 
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). 

这是我的代码

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelExec; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.Session; 

public class Basic { 
    public static void main(String[] args) { 
     String host = "dem.web.com"; 
     String user = "app"; 
     String password = "web"; 
     String command1 = "ssh ap[email protected]"; 
     try { 

      java.util.Properties config = new java.util.Properties(); 
      config.put("StrictHostKeyChecking", "No"); 
      JSch jsch = new JSch(); 
      com.jcraft.jsch.Session session = jsch.getSession(user, host, 22); 
      session.setPassword(password); 
      session.setConfig(config); 
      session.connect(); 

      Channel channel = session.openChannel("exec"); 
      ((ChannelExec) channel).setCommand(command1); 
      channel.setInputStream(null); 
      ((ChannelExec) channel).setErrStream(System.err); 

      InputStream in = channel.getInputStream(); 
      channel.connect(); 
      byte[] tmp = new byte[1024]; 
      while (true) { 
       while (in.available() > 0) { 
        int i = in.read(tmp, 0, 1024); 
        if (i < 0) 
         break; 
        System.out.print(new String(tmp, 0, i)); 
       } 
       if (channel.isClosed()) { 
        channel=session.openChannel("exec"); 
        break; 
       } 
       try { 
        Thread.sleep(1000); 
       } catch (Exception ee) { 
       } 
      } 
      channel.disconnect(); 
      session.disconnect(); 
      System.out.println("DONE"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
} 

有人可以帮助我吗?或者有更简单的方法吗? 谢谢。

回答

0

您正在尝试从dem.web.comweb。但是您不提供任何凭证或任何其他方法进行身份验证。所以认证自然失败。

无论如何,运行ssh不是实现隧道自动化的最佳方式。改为使用port forwarding

首先创建一个会话到dem.web.com,将本地端口(例如2222)转发到web:22。然后创建连接到localhost:2222的另一个会话。

请参阅http://www.jcraft.com/jsch/examples/PortForwardingL.java.html