我正在尝试使用 SSHJ 库在我的 Amazon EC2 计算机上执行 sudo 命令(https://github.com/shikhar/sshj https://github.com/shikhar/sshj)。不幸的是,我没有收到服务器的任何响应。我确信其他非 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.<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();
}
}
恐怕有点猜测,但我认为你的问题是:
// 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();
}
我认为,如果您只启动一个会话,在其上分配一个 PTY,然后在该会话上运行命令,您可能会感兴趣:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)