1.导入依赖
<dependencies>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
2.工具类
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* @author wuph
* @date 2022/6/5 17:27
*/
public class SSHTool {
private Connection conn;
private String ipAddr;
private Charset charset = StandardCharsets.UTF_8;
private String userName;
private String password;
public SSHTool(String ipAddr, String userName, String password, Charset charset) {
this.ipAddr = ipAddr;
this.userName = userName;
this.password = password;
if (charset != null) {
this.charset = charset;
}
}
/**
* 登录远程Linux主机
*
* @return 是否登录成功
*/
private boolean login() {
conn = new Connection(ipAddr);
try {
// 连接
conn.connect();
// 认证
return conn.authenticateWithPassword(userName, password);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 执行Shell脚本或命令
*
* @param cmds 命令行序列
* @return 脚本输出结果
*/
public StringBuilder exec(String cmds) throws IOException {
InputStream in = null;
StringBuilder result = new StringBuilder();
try {
if (this.login()) {
// 打开一个会话
Session session = conn.openSession();
session.execCommand(cmds);
in = session.getStdout();
result = this.processStdout(in, this.charset);
conn.close();
}
} finally {
if (null != in) {
in.close();
}
}
return result;
}
/**
* 解析流获取字符串信息
*
* @param in 输入流对象
* @param charset 字符集
* @return 脚本输出结果
*/
public StringBuilder processStdout(InputStream in, Charset charset) throws FileNotFoundException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
try {
int length;
while ((length = in.read(buf)) != -1) {
sb.append(new String(buf, 0, length));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb;
}
public static void main(String[] args) throws IOException {
SSHTool tool = new SSHTool("你的linux主机IP地址", "用户名", "密码", StandardCharsets.UTF_8);
StringBuilder exec = tool.exec("bash 脚本的路径");
System.out.println(exec);
}
}
注意事项:
确保脚本可以执行,如果出现以下错误:
请执行命令
chmod u+x demo.sh
其中demo.sh 为你要执行的文件的路径