1
我有代碼讓我通過ssh連接,運行一個命令並得到迴應。它工作正常,但僅適用於非交互式命令(如:ls
,df
,它們在運行後立即返回結果)。問題是當我試圖運行一些交互式命令,如top
或passwd
代碼正在等待響應(當然沒有)。如何應對交互式Linux命令?
如何應對交互式命令?我真的不關心輸出,我只是想運行它。
public String runCommand(String command) throws Exception {
// SSH Channel
ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
// Execute command
channelssh.setCommand(command);
channelssh.connect();
InputStream inputStream = channelssh.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append('\n');
}
channelssh.disconnect();
return stringBuilder.toString();
}