方法一
1. 导入gradle
# ssh2 2014版链接服务器
implementation group: 'ch.ethz.ganymed', name: 'ganymed-ssh2', version: '262'
2. Java代码如下
package com.xxx.core.utils;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import tk.mybatis.mapper.util.StringUtil; // 后面就判断用到 可已用 null && isEmpty() 代替,如果有tk的jar就用吧
import java.io.*;
/**
* FileName SSHConnection.java
* ----类
* @version 1.0.0
* @date 2021/3/22
*/
public class SSHConnection {
private static String DEFAULTCHART = "UTF-8";
private static Connection conn; // 静态变量 不要有set
private String ip;
private String userName;
private String userPwd;
public SSHConnection(String ip, String userName, String userPwd) {
this.ip = ip;
this.userName = userName;
this.userPwd = userPwd;
}
public SSHConnection() {}
public static void setCharset(String charset) {
DEFAULTCHART = charset;
}
public Connection getConn() {
return conn;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
/**
* 远程登录linux的主机
* @return 登录成功返回true,否则返回false
* @author Ickes
* @since V0.1
*/
public Boolean login() {
boolean flg = false;
try {
conn = new Connection(ip);
//连接
conn.connect();
//认证
flg = conn.authenticateWithPassword(userName, userPwd);
if (flg) {
System.out.println("成功连接!");
}
} catch (IOException e) {
e.printStackTrace();
}
return flg;
}
/**
* @param cmd 即将执行的命令
* @return 命令执行完后返回的结果值
* @author Ickes
* 远程执行shll脚本或者命令
* @since V0.1
*/
public String execute(String cmd) {
String result = "";
try {
if (login()) {
// 开启会话
Session session = conn.openSession();
//执行命令
session.execCommand(cmd);
result = processStdout(session.getStdout(), DEFAULTCHART);
//如果为得到标准输出为空,说明脚本执行出错了
if (StringUtil.isEmpty(result)) {
result = processStdout(session.getStderr(), DEFAULTCHART);
}
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* @param cmd 即将执行的命令
* @return 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null
* @author Ickes
* 远程执行shll脚本或者命令
* @since V0.1
*/
public String executeSuccess(String cmd) {
String result = "";
try {
if (login()) {
Session session = conn.openSession();//打开一个会话
session.execCommand(cmd);//执行命令
result = processStdout(session.getStdout(), DEFAULTCHART);
conn.close();
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 解析脚本执行返回的结果集
* @param in 输入流对象
* @param charset 编码
* @return 以纯文本的格式返回
* @author Ickes
* @since V0.1
*/
public 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 + "\n");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
public static void main(String[] args) {
// 服务器 ip地址 和 端口号
Connection conn = new Connection("192.168.xxx.xxx",22);
try {
conn.connect();
boolean flag = conn.authenticateWithPassword("xxx","xxx"); // 服务器 账户 和 密码
if (flag){
Session session2 = conn.openSession();
session2.execCommand("mysql -h 192.168.xxx.xxx -P 3306 -uroot -proot -e 'use teach_manager;select * from users;' -vvv"); // 这个是数据库的连接信息 后面的个数可以影响输出信息
System.out.println(processStdout(session2.getStdout(),DEFAULTCHART));
}else {
System.out.println(flag);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上已经完,,,如果需要简单的,请看以下代码
方法二
1. 导入gradle
# ssh工具
implementation group: 'com.jcraft', name: 'jsch', version: '0.1.55'
2. Java代码如下-->>已经包装可直接用
package com.etong.core.utils;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* FileName: SSHUtil.java
* 类的详细说明
* @version 1.0.0
* @date 2021/3/22
*/
public class SSHUtil {
// 服务器id地址
private String ip;
// 服务器用户名
private String userName;
// 服务器密码
private String password;
// 服务器端口
private Integer port;
// 需要执行的命令
private String cmd;
// 入参都为服务器的 ip 账户 密码 端口
public SSHUtil(String ip, String userName, String password, Integer port) {
this.ip = ip;
this.userName = userName;
this.password = password;
this.port = port;
}
// 执行命令的方法
public Map<String,String> runCommand(String runCmd) {
Map<String,String> isSuccess = new HashMap<>();
JSch jSch = new JSch();
try {
Session session = jSch.getSession(getUserName(), getIp(), getPort()); // 会话需要的信息
session.setPassword(getPassword()); // 服务器密码
session.setConfig("StrictHostKeyChecking", "no"); // 是否用密钥 这里是不要
session.connect(30 * 1000); // 请求时间 这里是30秒
Channel channel = session.openChannel("exec"); // 开启一个会话窗口
((ChannelExec) channel).setCommand(runCmd); // 需要执行的命令
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
StringBuilder res = new StringBuilder();
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
res.append(new String(tmp, 0, i));
}
isSuccess.put("result", res.toString()); // 命令执行后的返回结果 通过get("result")方法获取值
if (channel.isClosed()) {
if (in.available() > 0) {
continue;
}
isSuccess.put("status", String.valueOf(channel.getExitStatus()));
break;
}
}
channel.disconnect();
session.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
}
return isSuccess;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
}