我想通过JAVA API连接到Amazon EC2终端并执行sudo操作。我最终使用了SSHJ库,因为我发现它的界面非常简单易用。好的是,我甚至可以通过这个库执行sudo操作。以下是一些示例代码:
//启动新会话session=sshClient.startSession();session.allocateTY("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();
}
然而,我收到的回复中有控制字符,并希望将它们转换为纯文本。
Starting riak: [60G[[0;32m OK [0;39
经过大量研究,我使用"jansi"java库解决了这个问题(http://jansi.fusesource.org/)
所以现在我更新的代码看起来像这样:
Command cmd = null;
try (Session session = sshClient.startSession()) {
session.allocateDefaultPTY();
cmd = session.exec(command);
new StreamCopier(cmd.getInputStream(), AnsiConsole.out()).keepFlushing(true).copy();
cmd.join(timeout, timeUnit);
}finally{
if(cmd != null){
cmd.close();
}
}
而且,这很好用。