我正在使用以下代码来使用JSCH库获取命令的输出,
public SSHOutputBean executeCommand(String cmd, int timeOut) {
SSHOutputBean outputBean=new SSHOutputBean();
Channel ch=null;
try {
ch= this.session.openChannel("exec");
ChannelExec chExec= ((ChannelExec) ch);
chExec.setErrStream(System.err);
chExec.setInputStream(null);
chExec.setCommand("reset;"+cmd);
chExec.connect();
outputBean.setInputStream( chExec.getInputStream());
BufferedReader brInput = new BufferedReader(new InputStreamReader(outputBean.getInputStream()));
outputBean.setErrorStream(chExec.getErrStream());
BufferedReader brError = new BufferedReader(new InputStreamReader(outputBean.getErrorStream()));
while (true) {
try {
String result = brInput.readLine();
if (result == null)
break;
outputBean.getOutput().append(result+"\n");
} catch (Exception ex) {
ex.printStackTrace();
break;
}
}
while (true) {
try {
String result = brError.readLine();
if (result == null)
break;
outputBean.getError().append(result+"\n");
} catch (Exception ex) {
ex.printStackTrace();
break;
}
}
if (chExec.isClosed()) {
outputBean.setExitStatus(chExec.getExitStatus());
}
chExec.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSchException e){
e.printStackTrace();
}
finally
{
if(ch!=null)
ch.disconnect();
}
return outputBean;
}
问题是,如果客户端上的bashrc文件正在控制台上打印某些内容,那么每次我打开ChannelExec并运行命令时,都会出现这种情况。命令执行时给出的输出将与命令输出以及bashrc输出一样。我只想要命令的输出,而不是bashrc打印。
例如,
如果我在.bashrc文件中放置了以下代码
回显“欢迎用户”
如果我使用jsch运行命令,
SSHOutputBean sshOutputBean = ssh.executeCommand(“ uptime”);
那么输出是
欢迎用户(.bashrc输出)
13:15:10最多2天,1:53,8个用户,平均负载:0.14,0.06,0.06(实际命令输出)
但我希望输出是
13:15:10最多2天,1:53,8个用户,平均负载:0.14,0.06,0.06(实际命令输出)
请帮忙!
最佳答案
我假设您不能简单地将.bashrc更改为安静。如果您想隔离由于命令而导致的输出,并在此之前忽略任何内容,那么最好不要选择Exec通道。当您运行命令时,您的流将包含所有输出。
您可以尝试使用外壳代替。您可以连接它并让流读取所有初始输出(即“欢迎用户”或您的.bashrc文件中的其他输出)。然后刷新流,然后执行命令并读取流,以仅查看命令本身的输出。
或者,您可以使用channelExec进行处理。使用channel.setEnv(name,value)设置PS1变量以包含一些定界字符串。例如:
channel.setEnv("PS1","Command Starts Here::")
然后,您可以在分隔符“ Command Starts Here ::”上的提示符下解析输出。