package cn.ghostcloud.clusterservice.utils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Calendar;
/**
* @version 1.0
* @author: LWG
* @date: 2022-04-13 14:00
* java 实现连接SSH验证工具包
*/
@Slf4j
public class SshUtil {
private static String splitStr = "=====================";
/**
* 登录主机
* @return
* 登录成功返回true,否则返回false
*/
public static Connection SshLogin(String ip, String userName, String password){
boolean isAuthenticated = false;
Connection conn = null;
long startTime = Calendar.getInstance().getTimeInMillis();
String tipStr = "===========%s=========";
try {
conn = new Connection(ip);
conn.connect(); // 连接主机
// 认证
isAuthenticated = conn.authenticateWithPassword(userName, password);
if(isAuthenticated){
log.info(String.format(tipStr, "认证成功"));
} else {
log.info(String.format(tipStr, "认证失败"));
}
} catch (IOException e) {
log.error(String.format(tipStr, "登录失败"));
e.printStackTrace();
}
long endTime = Calendar.getInstance().getTimeInMillis();
log.info("登录用时: " + (endTime - startTime)/1000.0 + "s\n" + splitStr);
return conn;
}
/**
* 远程执行shell脚本或者命令
* @param cmd
* 即将执行的命令
* @return
* 命令执行完后返回的结果值
*/
public static String execute(Connection conn, String cmd){
String result = "";
Session session = null;
try {
if(conn != null){
// 打开一个会话
session = conn.openSession();
// 执行命令
session.execCommand(cmd);
String DEFAULT_CHAR_SET = "UTF-8";
result = processStdout(session.getStdout(), DEFAULT_CHAR_SET);
//如果标准输出为空,说明脚本执行出错
if(StringUtils.isBlank(result)){
log.info("【得到标准输出为空】\n执行的命令如下:\n" + cmd);
result = processStdout(session.getStderr(), DEFAULT_CHAR_SET);
}else{
log.info("【执行命令成功】\n执行的命令如下:\n" + cmd);
}
}
} catch (IOException e) {
log.error("【执行命令失败】\n执行的命令如下:\n" + cmd + "\n" + e.getMessage());
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
if (session != null) {
session.close();
}
}
return result;
}
/**
* 解析脚本执行返回的结果集
* @param in 输入流对象
* @param charset 编码
* @return
* 以纯文本的格式返回
*/
private static String processStdout(InputStream in, String charset){
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
String line = null;
while((line = br.readLine()) != null){
buffer.append(line).append("\n");
}
} catch (IOException e) {
log.error("解析脚本出错:" + e.getMessage());
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args){
// 输入服务器IP地址
String ip = "192.168.xx.xxx";
String userName = "xxx";
String password = "xxxxx";
Connection conn = SshUtil.SshLogin(ip, userName, password);
String cmd = "cd /home/miracle&&pwd&&ls&&cat lwg.txt";
String result = SshUtil.execute(conn, cmd);
log.info(splitStr + "\n执行的结果如下: \n" + result + splitStr);
log.info(String.valueOf(conn));
}
}
Java通过SSH登陆Linux服务器并执行命令(工具类)
最新推荐文章于 2024-05-20 16:21:46 发布