次のコードを使用して、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 ファイルに入れた場合
echo "ようこそユーザー"
jsch を使用してコマンドを実行すると、
SSHOutputBean sshOutputBean = ssh.executeCommand("稼働時間");
出力は、
ようこそユーザー(.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 (実際のコマンド出力)
助けてください!