java执行linux命令 su,如何执行linux命令“dzdo su - john”通过JSch java api并执行一些命令,如“ls -ltr”和在那个用户上...

本文档描述了一个Java程序,该程序使用JSch库尝试连接到远程Linux服务器,切换到另一个用户并执行命令。然而,程序在执行dzdosu-lucy命令后陷入无限循环,无法继续执行ls-ltr命令。作者推测可能是因为时间问题,并建议在两个println语句之间添加Thread.sleep或禁用PTY来解决此问题。
摘要由CSDN通过智能技术生成

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---}

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值