Java 操作SSH2实现远程执行linux命令
Posted Test_Box
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 操作SSH2实现远程执行linux命令相关的知识,希望对你有一定的参考价值。
1、引入依赖
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
2、SSH2Util 工具类封装
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SSH2Util {
//指定默认编码
private static String DEFAULT_CHARSET = "UTF-8";
/**
* 建立SSH2连接
* @param host 主机地址
* @param username 用户名
* @param password 密码
* @return Connection
*/
public static Connection openConnection(String host,String username,String password) {
try {
Connection connection = new Connection(host);
//建立ssh2连接
connection.connect();
//检验用户名
boolean login = connection.authenticateWithPassword(username,password);
if (login){
logger.info(host + " 连接成功");
return connection;
}else {
throw new RuntimeException(host + " 用户名密码不正确");
}
} catch (Exception e) {
throw new RuntimeException(host +" "+ e);
}
}
/**
* 执行命令
* @param connection ssh2连接对象
* @param command 命令语句
* @return 执行结果, 封装执行状态和执行结果
*/
public static ExecCmdResult execCommand(Connection connection,String command){
ExecCmdResult execCmdResult = new ExecCmdResult();
Session session = null;
try{
session = connection.openSession();
//执行命令
session.execCommand(command);
//解析结果
String result = parseResult(session.getStdout());
//解析结果为空,则表示执行命令发生了错误,尝试解析错误出输出
if (result == null||result.length()==0){
result = parseResult(session.getStderr());
}else {
execCmdResult.setSuccess(true);
}
//设置响应结果
execCmdResult.setResult(result);
logger.info(command + " ==>> " +execCmdResult.getResult());
return execCmdResult;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String parseResult(InputStream inputStream) throws IOException{
//读取输出流内容
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,DEFAULT_CHARSET));
StringBuffer resultSB = new StringBuffer();
String line;
while((line = br.readLine()) != null){
resultSB.append(line+"\\n");
}
//替换换行符
String result = resultSB.toString().replaceAll("[\\\\t\\\\n\\\\r]", "");
return result;
}
}
3、ExecCmdResult 定义返回结果类
public class ExecCmdResult {
//命令执行是否成功
private boolean success;
//输出结果
private String result;
public void setSuccess(boolean success){
this.success = success;
}
public String getResult(){
return result;
}
public void setResult(String result){
this.result = result;
}
}
4、SSH2Demo 测试
import ch.ethz.ssh2.Connection;
public class SSH2Demo {
public static void main(String[] args) {
try {
String host = "168.192.22.7";
String username = "root";
String password = "123456";
Connection connection = SSH2Util.openConnection(host,username,password);
String cpuInfo = "cat /proc/cpuinfo | grep \\"cpu cores\\" | uniq"; //服务器核数
ExecCmdResult cup = SSH2Util.execCommand(connection,cpuInfo);
connection.close();
}
catch (Exception a){
a.printStackTrace();
}
}
}
以上是关于Java 操作SSH2实现远程执行linux命令的主要内容,如果未能解决你的问题,请参考以下文章