如何实现一个Java程序中远程连接服务器执行一个脚本呢?有时候会有这种需求,如果非要去另外一个机器执行脚本,那么可以使用我下面这个工具类,已经封装好了,直接拿来用即可。
作者这里用Maven项目演示如何使用: 1)首先引入依赖:
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build209</version>
</dependency>
2)复制下面的工具类:RemoteShellExecutorUtils.java
/**
* RemoteShellExecutorUtils
*
* @author lcry
* @date 2019/08/24 18:00
*/
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class RemoteShellExecutorUtils {
private static final Logger LOG = LoggerFactory.getLogger(RemoteShellExecutorUtils.class);
private Connection conn;
private String ip;
private String usr;
private String psword;
private int port;
private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
/**
* 远程信息
*
* @param ip
* @param usr
* @param psword
*/
public RemoteShellExecutorUtils(String ip, int port, String usr, String psword) {
this.ip = ip;
this.usr = usr;
this.port = port;
this.psword = psword;
}
/**
* 远程登录
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip, port);
conn.connect();
return conn.authenticateWithPassword(usr, psword);
}
/**
* 执行命令
*
* @param cmds
* @return
* @throws IOException
*/
public String exec(String cmds) throws IOException {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
Session session = conn.openSession();
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
LOG.info("执行日志:[INFO] outStr=" + outStr);
stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
LOG.info("执行日志:[INFO] outErr=" + outErr);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
ret = session.getExitStatus();
} else {
LOG.error("执行日志:[INFO] ssh2 login failure:" + ip);
throw new IOException("SSH2_ERR");
}
} finally {
if (conn != null) {
conn.close();
}
if (stdOut != null) {
stdOut.close();
}
if (stdErr != null) {
stdErr.close();
}
}
return outStr;
}
private String processStream(InputStream in, String charset) throws IOException {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
/**
* 工具类
*
* @param usr 远程用户名
* @param password 远程密码
* @param serverIP 服务器IP
* @param port 端口 默认 22
* @param shPath 执行脚本
* @return 返回执行信息
*/
public static String ShellExecutor(String usr, String password, String serverIP, int port,
String shPath) {
RemoteShellExecutorUtils exe = new RemoteShellExecutorUtils(serverIP, port, usr, password);
String outInf = "";
try {
String cmd = shPath;
outInf = exe.exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
return outInf;
}
3)项目使用
RemoteShellExecutorUtils.ShellExecutor("root", "root", "192.168.254.140", 22, "/test.sh");
参数说明:
1.远程机器用户名
2.远程机器密码
3.远程机器IP
4.ssh端口号 默认22
5.需要执行的脚本