使用 JSch 执行'sudo su -'



我的代码有问题。我正试图成为sudo su -的root用户,但当执行它时,它会在控制台上显示:

已连接

#

并且没有通过下一行。

这是我的代码:

String command1 = "sudo su -";
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("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
OutputStream out = channel.getOutputStream();
channel.connect();
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();
}

sudo su -命令在当前shell中打开一个新的shell进程。

这个新的shell进程在收到exit命令之前不会结束。

由于您正在从Java向操作系统中的另一个进程发出命令,因此结果与您发出的命令挂起时的结果相同。

有两种方法可以解决这个问题:

  1. 只使用sudo来执行您真正需要的命令,方法是将sudo附加到每个命令中。

  2. 创建一个包装器脚本,该脚本将执行需要以root身份运行的所有命令,并使用sudo运行该脚本。

最新更新