Question

I am trying to execute a sudo command on my Amazon EC2 machine using the SSHJ library (https://github.com/shikhar/sshj). Unfortunately, I am not getting any response from the server. I know for sure that the other non-sudo commands get executed flawlessly. Here is some sample code.

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        sshClient.addHostKeyVerifier(new PromiscuousVerifier());
        sshClient.connect(host, 22);

        if (privateKeyFile != null) {
            // authenticate using private key file.
            PKCS8KeyFile keyFile = new PKCS8KeyFile();
            keyFile.init(privateKeyFile);
            sshClient.authPublickey(user, keyFile);
        } else {
            // Authenticate using password.
            sshClient.authPassword(user, password);
        }

        // Start a new session
        session = sshClient.startSession();
        session.allocatePTY("vt220", 80,24,0,0,Collections.<PTYMode, Integer>emptyMap());

            Command cmd = null;
                String response = null;
            try (Session session = sshClient.startSession()) {
             cmd = session.exec("sudo service riak start");
             response = IOUtils.readFully(cmd.getInputStream()).toString();
        cmd.join(timeout, timeUnit);
                } finally {
        if (cmd != null) {
            cmd.close();
        }
    }
Was it helpful?

Solution

It's a bit of a guess I'm afriad but I think your problem is:

    // Start a new session
    session = sshClient.startSession();
    session.allocatePTY("vt220", 80,24,0,0,Collections.<PTYMode, Integer>emptyMap());

    Command cmd = null;
    String response = null;
    // your allocating a new session there
    try (Session session = sshClient.startSession()) {

         cmd = session.exec("sudo service riak start");
         response = IOUtils.readFully(cmd.getInputStream()).toString();
         cmd.join(timeout, timeUnit);
    } finally {
        if (cmd != null) 
            cmd.close();
    }

I think if you start just a single session, allocate a PTY on it and then run a command on that session you might be in business:

    session = sshClient.startSession();
    session.allocatePTY("vt220", 80,24,0,0,Collections.<PTYMode, Integer>emptyMap());
    Command cmd = session.exec("sudo service riak start");
    String response = IOUtils.readFully(cmd.getInputStream()).toString();
    cmd.join(timeout, timeUnit);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top