使用sshj java库在我的Amazon EC2盒子上执行“sudo”命令

我正在尝试使用SSHJ库( https://github.com/shikhar/sshj )在我的Amazon EC2机器上执行sudo命令。 不幸的是,我没有收到服务器的任何回复。 我确信其他非sudo命令可以完美执行。 这是一些示例代码。

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

这是一个猜测我是afriad但我认为你的问题是:

  // Start a new session session = sshClient.startSession(); session.allocatePTY("vt220", 80,24,0,0,Collections.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(); } 

我想如果你只启动一个会话,在它上面分配一个PTY,然后在那个你可能在业务上的会话上运行一个命令:

  session = sshClient.startSession(); session.allocatePTY("vt220", 80,24,0,0,Collections.emptyMap()); Command cmd = session.exec("sudo service riak start"); String response = IOUtils.readFully(cmd.getInputStream()).toString(); cmd.join(timeout, timeUnit);