我正在尝试按特定顺序执行命令。
(1)连接到远程节点 ssh -i path-to-key root @ some-remote-node
(2)su user
使用JSCH做同样的事情时,我能够连接到远程节点。但是在执行下一个命令时,它会挂起。但是当我从终端做的时候,情况并没有发生。
代码,
private void execute(String command, Session session, long sleepTime,
boolean isCloseSession) throws JSchException, IOException {
System.out.println("Command \"" + command + "\" executed on HOST : "
+ session.getHost());
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command.trim());
String str = null;
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
StringBuilder sb = new StringBuilder();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i <= 0) {
break;
}
try {
Thread.sleep(sleepTime);
str = new String(tmp, 0, i);
sb.append(str);
channel.disconnect();
if (isCloseSession) {
closeSession();
}
} catch (Exception e) {
System.out.println(e.getClass()
+ " occured while calling execute(" + command
+ ", Session, " + sleepTime + ")");
}
}
exitCode = channel.getExitStatus();
if (channel.isClosed()) {
break;
}
}
response = sb.toString();
if (isCloseSession) {
closeSession();
}
}
public void executeCommand(String command, boolean isCloseSession) {
executeCommand(command, 0, isCloseSession);
}
public void executeCommand(String command, long sleepTime,
boolean isCloseSession) {
try {
session = createSession(basicInfo);
if (session != null) {
if(!session.isConnected()) {
session.connect();
}
execute(command, session, sleepTime);
} else {
System.out.println("Session is NULL!");
}
} catch (JSchException ex) {
System.out.println("Connection to HOST \"" + basicInfo.getHostName() + "\" failed"
+ ex.getStackTrace());
} catch (IOException ex) {
System.out.println("Unable to execute the command \"" + command
+ "\" on the HOST \"" + this.basicInfo.getHostName()
+ "\" : " + ex.getStackTrace());
}
}
public static void main(String[] args) {
SSHUtil util = new SSHUtil(hostName, userName, keyFile);
util.executeCommand("ls", false); // For this I'm getting response
System.out.println(util.getResponse());
util.executeCommand("su hdfs", false); // For this, its going into while(true) {} and breaking no where.
System.out.println(util.getResponse());
}