dehsams123
dehsams123

Reputation: 251

Java program hangs after executing sudo su command?

I have a program that can ssh into a remote host and remotely execute commands after that. Commands like mkdir and cd work but when I try to execute the command sudo su - username the program just hangs. I was wondering if there's anything missing/wrong in my code.

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();
}

Also, I need to ssh from this host to another host after I sudo, so basically I need to ssh to a remote host via a gateway kind of a thing and then connect to a database, once this problem gets fixed.

Any light on this will be greatly appreciated.

Thanks.

Upvotes: 2

Views: 4353

Answers (1)

ymnk
ymnk

Reputation: 1155

The sudo command will require the pty. Refer to http://www.jcraft.com/jsch/examples/Sudo.java.html for doing sudo on the exec channel, and as for jump-hosts, refer to http://www.jcraft.com/jsch/examples/JumpHosts.java.html

Upvotes: 1

Related Questions