2016-05-09 28 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