java jsch 切换用户_java – JSch – 如何以我切换到的用户发出...

这篇博客探讨了如何使用Java的JSch库从Windows 7远程连接到Linux服务器,并按照特定流程切换到root用户,然后进一步切换到'someuser'。作者已完成登录和切换到root用户的过程,询问在root权限下执行`su`命令切换用户的方法,或者是否有直接以root身份执行后续命令的方式。文中提供了一个示例代码片段展示当前尝试的操作。
摘要由CSDN通过智能技术生成

我正在使用Jsch从Windows 7远程连接到Linux服务器.

我必须

(i) login to Linux server with my credentials

(ii) switch to root using a pmrun command [this is the procedure in our environment], and

(iii) execute su command to switch as "someuser"

(iv) execute further commands as that "someuser"

我完成了步骤(i)和(ii).

在完成步骤(ii)之后,来自通道的InputStream将命令提示符显示为root用户的命令提示符.所以我假设我现在已成为root用户.

现在,我是否需要让root用户的会话进一步执行su命令,或者有没有办法以root用户身份执行更多命令?

有人请帮忙.谢谢.

更新:源代码

public class Pmrun {

public static void main(String[] arg){

try{

JSch jsch=new JSch();

String host=null;

if(arg.length>0){

host=arg[0];

}

else{

host="myself@linuxserver.com";

}

String user=host.substring(0, host.indexOf('@'));

host=host.substring(host.indexOf('@')+1);

Session session=jsch.getSession(user, host, 22);

UserInfo ui=new MyUserInfo();

session.setUserInfo(ui);

session.connect();

String command= "pmrun su -";

Channel channel=session.openChannel("exec");

((ChannelExec)channel).setCommand(command);

InputStream in = channel.getInputStream();

OutputStream outStream = channel.getOutputStream();

((ChannelExec)channel).setPty(true);

((ChannelExec)channel).setErrStream(System.err);

channel.connect();

TimeUnit.SECONDS.sleep(10);

outStream.write("xxxxxxx

".getBytes());

outStream.flush();

((ChannelExec)channel).setCommand("su - someuser");

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();

}

catch(Exception e){

System.out.println(e);

}

}

public static class MyUserInfo implements UserInfo{

public String getPassword(){ return passwd; }

public boolean promptYesNo(String str){

str = "Yes";

return true;}

String passwd;

public String getPassphrase(){ return null; }

public boolean promptPassphrase(String message){ return true; }

public boolean promptPassword(String message){

passwd="zzzzzzzz";

return true;

}

public void showMessage(String message){

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值