java远程执行linux服务器上的shell脚本

时间:2021-09-12 06:12:23

业务场景:需要从服务器A中新增的文件同步至本地服务器,服务器A中内存有限,需同步成功之后清除文件。

Java调用远程shell脚本,需要和远程服务器建立ssh链接,再调用指定的shell脚本。

1.创建清除文件shell脚本,可以使用touch或者vi命令

#创建sh文件
vi file_clear.sh #file_clear.sh内容如下
#!/bin/bash
#将日志定向输出到/opt/data/logs路径下,以当前日期为日志名称
echo "执行公告数据文件清空定时任务,执行时间$(date -d "now" "+%Y-%m-%d %H:%M:%S")"
>> /opt/data/logs/$(date -d "now" +%Y-%m-%d).log
#指定目标路径并删除
find /opt/data/files/temp/ -type d | xargs rm -rf

  给file_clear.sh文件赋予可执行权限

chmod +x file_clear.sh

  

2.pom.xml中引入ganymed-ssh2依赖

java远程执行linux服务器上的shell脚本
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>

3.新建ssh连接类SSHClient,用于与远程服务器建立连接,参数可在yml文件或者properties文件中指定

package com.xie.api;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import org.springframework.beans.factory.annotation.Value; import java.io.IOException;
import java.nio.charset.Charset; public class SSHClient { private String ip;
private String username;
private String password; private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60; private Connection conn; public SSHClient(String ip, String username, String password) {
this.ip = ip;
this.username = username;
this.password = password;
} /**
* 登录指远程服务器
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection(ip);
conn.connect();
return conn.authenticateWithPassword(username, password);
} public int exec(String shell) throws Exception {
int ret = -1;
try {
if (login()) {
Session session = conn.openSession();
session.execCommand(shell);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
ret = session.getExitStatus();
} else {
throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
}
} finally {
if (conn != null) {
conn.close();
}
}
return ret;
} public static void main(){
try {
SSHClient sshClient = new SSHClient("服务器A ip", "username", "password");
sshClient.exec("服务器shell脚本路径");
} catch (Exception e) {
e.printStackTrace();
}
}
}

深漂码农整理,定期干货分享,自我梳理,一同成长​​