【发布时间】:2019-11-16 16:00:43
【问题描述】:
我的代码有问题。我正在尝试使用 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 时,它会要求输入密码。
-
用
sudo su -u username替换你的命令。我认为这将解决您的问题。 -
这个问题已经被问过很多次了。请在发布问题之前搜索您的问题。 -- 参见例如Running command after sudo login 或Executing sudo using SSH “exec” channel in JSch。