[英]How to execute linux command “dzdo su - john” through JSch java api and execute some commands like “ls -ltr” on that user
我想使用java jsch庫連接到遠程linux服務器,並使用dzdo su-john命令切換到另一個用戶,我想對該用戶執行一些命令。 我已經嘗試了幾種方法來滿足此要求,但是我無法做到這一點,對此可以提供任何幫助。
public static void main(String args[])
{
String host="xxxxx.yyyy.com";
String user="user";
String password="password";
String command1="dzdo su - lucy";
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println(command1);
ps.println("ls -ltr");
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()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}
}
}
通過執行此代碼,我得到這樣的輸出,並且程序沒有停止
Connected
Last login: Thu Oct 4 13:24:38 2018 from xx.xx.xxx.xx
$ dzdo su - lucy
xxxx@zr1.xxxx.com:/u/zr1.xxxx.com/lucy $
命令ls -ltr沒有執行。 該程序將在語句while(true){--- code ---}中進入無限循環
這可能是時間問題。
考慮在兩個println
調用之間添加Thread.sleep
。
ps.println(command1);
Thread.sleep(1000);
ps.println("ls -ltr");
或者嘗試禁用PTY:
((ChannelShell)channel).setPty(false);
channel.connect();
如果可行,那將是比延遲更可靠的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.