gpt4 book ai didi

Java程序执行sudo su命令后挂起?

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:00 26 4
gpt4 key购买 nike

我有一个程序,可以ssh到远程主机,然后远程执行命令。像 mkdircd 这样的命令可以工作,但是当我尝试执行命令 sudo su - username 时,程序就会挂起。我想知道我的代码中是否有任何遗漏/错误。

JSch jSch = new JSch();
Channel channel = null;
Session session = null;
InputStream in = null;
String username;
OutputStream os = null;;

try {
Properties conf = new Properties();
conf.put("StrictHostKeyChecking", "no");

jSch.addIdentity("id_rsa");
jSch.setConfig(conf);
session = jSch.getSession("username", "hostname", 22);

String cmd = "mkdir test";
session.connect(); // creating the ssh connection

channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setCommand(cmd);
channel.setInputStream(null);
in = channel.getInputStream(null);
channel.connect();

byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
}
if (channel.isClosed()) {
break;
}
try {
Thread.sleep(1000); // to wait for long running process ..
} catch (Exception ee) {
}
String value = new String(tmp);
System.out.println("input stream " + value);
}
}catch(Exception e){
e.printStackTrace();
}finally{
channel.disconnect();
session.disconnect();
if(in!=null)
in.close();
}

此外,在执行 sudo 之后,我需要从该主机 ssh 到另一台主机,所以基本上,一旦这个问题得到解决,我需要通过网关之类的东西 ssh 到远程主机,然后连接到数据库。

对此的任何了解都将不胜感激。

谢谢。

最佳答案

sudo 命令需要 pty。引用http://www.jcraft.com/jsch/examples/Sudo.java.html对于在 exec channel 上执行 sudo 以及跳转主机,请参阅 http://www.jcraft.com/jsch/examples/JumpHosts.java.html

关于Java程序执行sudo su命令后挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11234219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com