我試圖連接到主機,然後使用「su - john」更改用戶,然後以john身份執行命令。僅使用JSch可能嗎?Java JSch更改遠程計算機上的用戶並執行命令
問題是,我創建會話並打開通道並執行上述命令後,它應該請求密碼,但沒有任何反應。
這是我如何連接到遠程機器:
try
{
Channel channel = session.openChannel("exec");
channel.setInputStream(null);
channel.setOutputStream(System.out);
((ChannelExec) channel).setCommand(command);
channel.connect();
InputStream in = channel.getInputStream();
byte[] tmp = new byte[1024];
while (true)
{
while (in.available() > 0)
{
int i = in.read(tmp, 0, 1024);
if (i < 0)
{
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed())
{
break;
}
try
{
Thread.sleep(1000);
}
catch (Exception ee)
{
}
}
channel.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
是否必須創建另一個信道,當I:
String address = "myremote.computer.com";
JSch jsch = new JSch();
String user = "tom";
String host = address;
String password = "l33tpaSSw0rd";
Session session = jsch.getSession(user, host, 22);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(password);
session.connect();
然後我經由runSshCommand()
方法,它看起來像這樣執行命令改變用戶,或如何使這項工作?
因爲如果我使用
runSshCommand("su - john",session);
runSshCommand("tail -1 ~/mylog.log",session);
它只是執行「蘇」命令,但它並沒有完成用戶的變化和事後執行「尾巴」將導致一個錯誤,因爲「湯姆」不是招」 t得到的文件:/
基本上我想我的應用程序連接到機器,更改用戶,讀取一個文件並返回數據。任何人都可以點亮一下嗎?