问题
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 $
the command ls -ltr was not executing. The program was going to infinite loop in the statement while(true){---code---}
回答1:
It might be a timing issue.
Consider adding Thread.sleep
between the two println
calls.
ps.println(command1);
Thread.sleep(1000);
ps.println("ls -ltr");
Or try disabling PTY:
((ChannelShell)channel).setPty(false);
channel.connect();
If that works, it's a more robust solution than the delay.
来源:https://stackoverflow.com/questions/52644221/how-to-execute-linux-command-dzdo-su-john-through-jsch-java-api-and-execute