如何执行linux命令“dzdo su - john”通过JSch java api并执行一些命令,如“ls -ltr”和在那个用户上 [英] 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切换到另一个用户,我想在该用户上执行一些命令。我已经尝试了几种方法来满足这个要求,但我无法做到这一点,任何人都可以提供帮助。
I want to connect to the remote linux server using java jsch library and switch to another user using command dzdo su - john and I want to execute some commands on that user. I have tried several ways on this requirement but I am unable to do this could any one help on this.
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();
}
}
}
执行这段代码我得到这样的输出,程序没有暂停
by executing this code I am getting an output like this and the program is not halting
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未执行。该程序在语句中将无限循环,而(true){--- code ---}
the command ls -ltr was not executing. The program was going to infinite loop in the statement while(true){---code---}
推荐答案
它可能是一个时间问题。
It might be a timing issue.
考虑在两个 println
之间添加 Thread.sleep
电话。
Consider adding Thread.sleep
between the two println
calls.
ps.println(command1);
Thread.sleep(1000);
ps.println("ls -ltr");
或尝试禁用PTY:
Or try disabling PTY:
((ChannelShell)channel).setPty(false);
channel.connect();
如果可行的话,这是一个比延迟更强大的解决方案。
If that works, it's a more robust solution than the delay.
这篇关于如何执行linux命令“dzdo su - john”通过JSch java api并执行一些命令,如“ls -ltr”和在那个用户上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!