1.利用Linux Shell写了两个脚本,一个是重启进程,一个是关闭进程代码如下:
#!/bin/bash
pid=$(ps -ef | grep "test" | grep -v grep | awk '{print $2}')
#echo "$pid"
if [ -z "$pid" ];then
echo "没有此进程"
exit 1
fi
for id in $pid
do
kill -9 $id
echo "$id"“已经被杀死”
done
nohup java -jar /home/test.jar &
echo "重启项目"
echo "此进程被调用"
#!/bin/bash
pid=$(ps -ef | grep "test" | grep -v grep | awk '{print $2}')
#echo "$pid"
if [ -z "$pid" ];then
echo "没有此进程"
exit 1
fi
for id in $pid
do
kill -9 $id
echo "$id"“已经被杀死”
done
echo "此脚本被调用"
以上是放在服务器上的两个Linux shell脚本用来重启进程,关闭进程,我们要把此进程赋权,添加可执行的权限
chmod +x 脚本
然后就是JAVA调用
package com.data.scheduled;
import java.io.IOException;
import java.nio.charset.Charset;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
/**
* 实现远程调用服务器上的脚本
* @author xjw
* @Description: 该类的功能描述
* @See SSHClient.java
* @Version 2020年8月5日
*
*/
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(String[] args){
try {
SSHClient sshClient = new SSHClient("ip地址", "用户名", "密码");
System.out.println(sshClient.exec("脚本路径"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行JAVA程序即可调用成功。