我有两台机器dev服务器和已存储日志的日志服务器,我想先ssh到dev服务器,然后从那里我要ssh到log服务器执行一些脚本。 下面是我尝试使用jsch的代码:
获取jschSession:
private Session getSSHSession(String user,String host,String password) {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
Session session = null;
try {
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
} catch (JSchException e) {
e.printStackTrace();
}
return session;
}
执行命令
private String execute(Session session, String cmd) {
StringBuffer sb = new StringBuffer();
try{
Channel channel=session.openChannel("exec");
((ChannelExec) channel).setPty(true);
((ChannelExec)channel).setCommand(cmd);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String msg = null;
while ((msg = br.readLine())!=null) {
sb.append(msg);
}
System.out.println("------------msg: -----------"+sb.toString());
while(true){
System.out.println("channel.getExitStatus(): "+channel.getExitStatus());
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
if(channel.getExitStatus()==0) {
System.out.println("script executed successfully..........");
}
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
调用执行
public String audit(AuditRequest request) {
Session session = getSSHSession(user,host,password);
String cmd = "ssh user@server; cd /mmt/test;ls -ltr";
String result = execute(session,cmd);
System.out.println("cmd1: "+cmd+" result: -------------"+result);
return result;
}
因此,基本上,我首先要连接到开发服务器,然后使用其会话尝试执行ssh命令以连接到日志服务器。 通过发布的代码,我可以连接到我的开发机,但无法从那里进行ssh到日志机。
如果我删除以下((ChannelExec) channel).setPty(true);
是我得到的错误:
Pseudo-terminal will not be allocated because stdin is not a terminal.
Permission denied, please try again.
Permission denied, please try again.
如果我将setPty用于伪终端,它将卡在channel.connect();
使用channel.setPty(true)阅读很多提到的帖子/问题,但这似乎不起作用
有人可以帮我知道这是怎么回事。
谢谢