执行“sudo”使用sshj java库在我的Amazon EC2盒子上命令 [英] Executing "sudo" command on my Amazon EC2 box using sshj java library
问题描述
我正在尝试使用SSHJ库在我的Amazon EC2机器上执行sudo命令( https:// github。 COM / Shikhar的/ sshj )。不幸的是,我没有收到服务器的任何回复。我确信其他非sudo命令可以完美执行。以下是一些示例代码。
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();
}
}
推荐答案
这是有点猜测我不知道但我认为你的问题是:
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();
}
我想如果你只开始一个会话,就在它上面分配一个PTY然后在你可能正在营业的那个会话上运行一个命令:
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);
这篇关于执行“sudo”使用sshj java库在我的Amazon EC2盒子上命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!