从ssh命令以创建命令的相同顺序记录stdout和stderr
问题内容:
简短版本: 是否可以将sdout和stderr记录在通过ssh远程执行的命令的本地端上,其顺序与在远程主机上输出的顺序相同?如果是这样,怎么办?
长版:
我试图记录远程执行的SSH命令(使用Jsch)的标准和错误输出,其顺序与远程命令的输出顺序相同。换句话说,如果远程命令将“ a”写入stdout,然后将“
b”写入stderr,然后将“ c”写入stdout,则我希望客户端(本地)端的日志读取为:
a
b
c
以下是我到目前为止的内容。它相对接近我想要的,但是我认为很明显,它不能保证客户端的正确输出顺序。
public int exec(String strCommand) throws ExceptionUnableToExecCommand {
JSch jsch = new JSch();
Session session = null;
ChannelExec channel = null;
try {
session = jsch.getSession(user, host, 22);
UserInfo ui = new cyclOps.jsch.UserInfo(password);
session.setUserInfo(ui);
session.connect();
channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(strCommand);
channel.setInputStream(null);
InputStream in = channel.getInputStream();
InputStream err = channel.getErrStream();
channel.connect();
/* getOutput() defined below. */
return this.getOutput(channel, in, err);
} catch (JSchException | IOException e) {
throw new ExceptionUnableToExecCommand("Unable to execute " + strCommand + " " + this.toString(), e);
} finally {
if (channel != null) channel.disconnect();
if (session != null) session.disconnect();
}
}
private int getOutput(ChannelExec channel, InputStream in, InputStream err) throws IOException {
byte[] tmp = new byte[1024];
while(true){
while(in.available() > 0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
this.sshLogger.logOutputFromSSH(new String(tmp, 0, i));
}
while(err.available() > 0){
int i=err.read(tmp, 0, 1024);
if(i<0)break;
this.sshLogger.logOutputFromSSH(new String(tmp, 0, i));
}
if(channel.isClosed()){
return channel.getExitStatus();
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
}
我想我应该指出,这是Jsch网站示例中Exec.java的修改版本。
问题答案:
下面的代码块怎么样?
channel.setCommand(command);
PipedOutputStream pos=new PipedOutputStream();
PipedInputStream pis=new PipedInputStream(pos);
channel.setOutputStream(pos);
channel.setExtOutputStream(pos);
InputStream in=pis;
channel.connect();