连接SSH客户端,操作命令
测试目前所知的几种ssh命令执行的操作api。
一、SSH2
2014年后就没有更新了
每次只能单命令执行,多个命令下发需要用 && 合并起来,结果会整体返回
无法链式执行。否则会报 A remote execution has already started 异常
1、依赖
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
2、案例
// 创建连接
Connection connection = new Connection(remoteInfo.getUrl(), remoteInfo.getPort());
connection.connect();
connection.authenticateWithPassword(remoteInfo.getUsername(), remoteInfo.getPassword());
// 打开会话窗口
Session session = connection.openSession();
StreamGobbler is = new StreamGobbler(session.getStdout());
// 发送命令
session.execCommand(command, "GB2312");
// 获取结果
BufferedReader br = new BufferedReader(new InputStreamReader(is, DEFAULT_CHART));
String line;
while (null != (line = br.readLine())) {
LOGGER.info("line=" + line);
}
// 关闭
session.close();
connection.close();
二、JSCH
纯Java实现。依赖于JavaTm Cryptography Extension(JCE)
支持链式命令执行,执行每个命令后可以获取返回的结果,就是返回数据格式比较复杂
1、依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2、案例
// 创建JSCH
JSch ssh = new JSch();
Session session = ssh.getSession(remoteInfo.getUsername(), remoteInfo.getUrl(), remoteInfo.getPort());
session.setPassword(remoteInfo.getPassword());
// 这里是 屏蔽掉验证
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(200000);
session.connect(60000);
// 打开shell,windows可以用 exec
ChannelShell shell = (ChannelShell) session.openChannel("shell");
// 创建 数据读取流
PrintStream outputStream = new PrintStream(shell.getOutputStream(), false, DEFAULT_CHART);
InputStreamReader reader = new InputStreamReader(shell.getInputStream(), DEFAULT_CHART);
BufferedReader reader = new BufferedReader(reader);
shell.connect(60000);
// 命令执行
outputStream.println(msg);
outputStream.flush();
// 结果读取
int len = 0;
while (len < 0) {
char[] values = new char[1024];
len = reader.read(values);
if (len > 0) {
String s = new String(values, 0, len);
LOGGER.info("line=" + s);
}
}
// 关闭
shell.disconnect();
session.disconnect();
三、SSHD
Apache sshd是一个SSH协议的100%纯Java库,支持客户端和服务器。sshd库基于Apache MINA项目(可伸缩高性能的异步IO库)。
1、依赖
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-scp</artifactId>
<version>2.9.0</version>
</dependency>
2、案例
// 创建连接ssh客户端
SshClient client = SshClient.setUpDefaultClient();
client.open();
ConnectFuture connect = client.connect(remoteInfo.getUsername(), remoteInfo.getUrl(), remoteInfo.getPort());
// 创建会话
ClientSession session = connect.verify().getSession();
session.addPasswordIdentity(remoteInfo.getPassword());
session.auth().verify(TimeUnit.SECONDS.toMillis(0L));
// 这里打开shell命令窗口,window是 Exec
ChannelShell shellChannel = session.createShellChannel(command);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
shellChannel.setOut(outputStream);
shellChannel.open();
shellChannel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED, 0L));
// 关闭
session.close();
client.close();