我正在使用 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) 后, channel 中的 InputStream 将显示 root 用户的命令提示符。所以我假设我现在已经成为root用户了。
现在,我是否需要获取 root 用户的 session 来进一步执行 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\n".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){
}
}
}
最佳答案
使用“exec” channel ,您只能执行单个命令。
另一个命令在 su
内执行,而不是在 su
之后执行。
一种解决方案是在
su
命令行上提供其他命令,例如:su -c command
或使用其标准输入将命令提供给
su
:outStream.write(("command\n").getBytes());
一般来说,我推荐第一种方法,因为它使用定义更好的 API(命令行参数)。
关于java - JSch - 如何以我切换到的用户身份发出命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097999/