[英]Connecting to server via SSH using Java - JSch and issuing shell commands
[英]Executing ssh on remote server to jump to another server and execute further commands there using Java and JSch
我正在嘗試使用 JSch 庫通過 SSH 在遠程機器上執行多個命令。 我快到了,但卡在一個命令中。
我正在使用兩台遠程機器讓我們說 RM1 和 RM2
能夠做到以下步驟,
無法執行此步驟, 1. 一旦我將連接到遠程機器 RM2,此后無法執行任何命令。
請讓我知道是否有人可以幫助我。
我試過這個代碼:
String host="IP";
String user="username";
String password="password";
String command1="pwd";
String command2="ssh -tt user@ip";
String command3="pwd";
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel1=session.openChannel("exec");
((ChannelExec)channel1).setCommand(command1;command2;command3);
channel1.setInputStream(null);
((ChannelExec)channel1).setErrStream(System.err);
InputStream in1=channel1.getInputStream();
channel1.connect();
byte[] tmp=new byte[1024];
while(true){
while(in1.available()>0){
int i=in1.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel1.isConnected()){
System.out.println("exit-status: "+channel1.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
嘗試在連接到 RM1 的普通 SSH 終端客戶端中執行pwd;ssh -tt user@ip;pwd
。 它不會工作,所以它也不會在 Java 中工作。
要進行“跳轉”,您應該使用端口轉發(參見JSch JumpHosts
示例),而不是在跳轉服務器上執行ssh
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.