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

时间:2012-06-27 20:18:01

标签: java ssh channel jsch

我有一个程序可以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();
}

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

对此我们将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:1)

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

相关问题