Executing “sudo” command on my Amazon EC2 box using sshj java library

纵饮孤独 提交于 2019-12-21 06:02:05

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/20406425/executing-sudo-command-on-my-amazon-ec2-box-using-sshj-java-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!