Ubuntu设置jar包自启动java脚本
导入一个依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
创建AutoStartJar.java文件复制以下代码,只有写了需要修改的地方进行修改即可
package com.ex.demo.autoStart;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AutoStartJar {
/**
* ubuntu服务器的ip 自行修改你的ip
*/
public static final String IP = "192.168.1.17";
/**
* ubuntu服务器连接用户名 自行修改你的用户名
*/
public static final String USR = "***";
/**
* ubuntu服务器连接密码 自行修改你的密码
*/
public static final String PSWORD = "***";
/**
* jar包要部署到ubuntu服务器上的位置
*/
public static final String DEPLOY_PATH = "/home/***/***";
/**
* 是否部署开机自启
*/
public static final boolean AUTO_START = true;
/**
* 是否上传后直接启动
*/
public static final boolean IMMEDIATELY_START = false;
/**
* 本地存放要部署jar包和生成辅助文件的位置 文件夹内只能一次放一个jar包
*/
public static final String LOCAL_BASE_PATH = "E:\\自动化部署";
/**
* jar日志文件名称
*/
public static final String LOG_FILE_NAME = "log.log";
/**
* ubuntu存放自动启动service文件目录 一般Ubuntu都是这个文件夹,不是就自行修改
*/
public static final String AUTO_START_SERVICE_PATH = "/etc/systemd/system/";
/**
* ubuntuJAVA安装位置 命令行使用which java获取 自行修改
*/
public static final String JAVA_Home = "/usr/bin/java";
public static void main(String[] args) throws Exception {
// System.out.println("ubuntu服务器的ip = " + IP);
// System.out.println("ubuntu服务器连接用户名 = " + USR);
// System.out.println("ubuntu服务器连接密码 = " + PSWORD);
// System.out.println("本地存放要部署jar包和生成辅助文件的位置 = " + LOCAL_BASE_PATH);
// System.out.println("jar包要部署到ubuntu服务器上的位置 = " + DEPLOY_PATH);
// System.out.println("jar日志文件名称 = " + LOG_FILE_NAME);
// System.out.println("ubuntu存放自动启动service文件目录 = " + AUTO_START_SERVICE_PATH);
// System.out.println("是否部署开机自启 = " + AUTO_START);
// System.out.println("是否上传后直接启动 = " + IMMEDIATELY_START);
// System.out.println();
SSH ssh = new SSH(IP, USR, PSWORD);
ssh.login();
File jarFile = getJarFile(LOCAL_BASE_PATH);
if (jarFile == null) {
System.out.println("未找到jar包无法部署");
return;
}
System.out.println("开始自动化部署...");
// String javaHome = ssh.exec("which java");
String javaHome = "";
// System.out.println("javaHome = " + javaHome);
if (StrUtil.isEmpty(javaHome)) {
javaHome = JAVA_Home;
}
String jarFileName = jarFile.getName();
String originName = jarFileName.replace(".jar", "");
System.out.println("jar包文件名称 = " + jarFileName);
String startShFileName = "start-" + originName + ".sh";
String closeShFileName = "close-" + originName + ".sh";
String restartShFileName = "restart-" + originName + ".sh";
String startShText = "#!/bin/sh\n" +
"export JAVA_HOME=" + javaHome + "\n" +
"export PATH=$JAVA_HOME/bin:$PATH\n" +
"cd " + DEPLOY_PATH + "\n" +
"nohup java -jar " + DEPLOY_PATH + "/" + jarFileName + " >>" + LOG_FILE_NAME + " 2>&1 &";
String closeShText = "ps -ef | grep -v grep | grep " + jarFileName + " | awk '{ print \" kill -9 \" $2 }' | sh ";
String restartShText = "sh " + closeShFileName + ";\n" +
"echo \"\">" + LOG_FILE_NAME + ";\n" +
"sh " + startShFileName + ";\n" +
"tail -f " + LOG_FILE_NAME;
File startShFile = FileUtil.touch(LOCAL_BASE_PATH,startShFileName);
File closeShFile = FileUtil.touch(LOCAL_BASE_PATH,closeShFileName);
File restartShFile = FileUtil.touch(LOCAL_BASE_PATH,restartShFileName);
FileWriter startShFileWriter = new FileWriter(startShFile);
FileWriter closeShFileWriter = new FileWriter(closeShFile);
FileWriter restartShFileWriter = new FileWriter(restartShFile);
startShFileWriter.write(startShText);
closeShFileWriter.write(closeShText);
restartShFileWriter.write(restartShText);
startShFileWriter.flush();
closeShFileWriter.flush();
restartShFileWriter.flush();
ssh.putFile(startShFile, DEPLOY_PATH);
ssh.putFile(closeShFile, DEPLOY_PATH);
ssh.putFile(restartShFile, DEPLOY_PATH);
ssh.putFile(jarFile, DEPLOY_PATH);
if (IMMEDIATELY_START) {
String cmd = "sh " + DEPLOY_PATH + "/" + startShFile.getName();
System.out.println("启动jar包 = " + cmd);
ssh.execCmd(cmd);
}
if (AUTO_START) {
String autoStartServiceFileName = "autostart-" + originName + ".service";
File autoStartServiceFile = FileUtil.touch(LOCAL_BASE_PATH, autoStartServiceFileName);
FileWriter autoStartServiceFileWriter = new FileWriter(autoStartServiceFile);
String autoStartServiceText = "[Unit]\n" +
"Description=autoStart-" + jarFileName + "\n" +
"After=syslog.target network.target\n" +
"\n" +
"[Service]\n" +
"ExecStart=" + javaHome + " -jar " + DEPLOY_PATH + "/" + jarFileName + "\n" +
"[Install]\n" +
"WantedBy=multi-user.target\n";
autoStartServiceFileWriter.write(autoStartServiceText);
autoStartServiceFileWriter.flush();
String startServiceFileName = autoStartServiceFile.getName();
// ssh.putFile(autoStartServiceFile, AUTO_START_SERVICE_PATH);
ssh.putFile(autoStartServiceFile, DEPLOY_PATH);
String cmd = "cp " + DEPLOY_PATH + "/" + startServiceFileName + " " + AUTO_START_SERVICE_PATH + startServiceFileName;
System.out.println("cp命令:");
System.out.println(cmd);
ssh.execCmd(cmd);
String exec = ssh.exec(cmd);
if (StrUtil.isNotEmpty(exec)) {
System.out.println("exec = " + exec);
}
String cmd1 = "systemctl enable " + autoStartServiceFileName;
System.out.println("开机启动命令:");
System.out.println(cmd1);
ssh.execCmd(cmd1);
String exec1 = ssh.exec(cmd1);
if (StrUtil.isNotEmpty(exec1)) {
System.out.println("exec1 = " + exec1);
}
}
}
private static File getJarFile(String s) {
for (File file : FileUtil.touch(s).listFiles()) {
if ("jar".equals(FileUtil.getSuffix(file))) {
return file;
}
}
return null;
}
}
创建SSH.java文件复制一下代码
package com.ex.demo.autoStart;
import ch.ethz.ssh2.*;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.StrUtil;
import java.io.*;
import java.util.Objects;
public class SSH {
private String ip;
private String usr;
private String psword;
public SSH(String ip, String usr, String psword) {
this.ip = ip;
this.usr = usr;
this.psword = psword;
}
private Connection connection;
/**
* 获取文件流
*
* @param fileName 服务器文件
*/
public InputStream copyFile(String fileName) {
SCPClient sc = new SCPClient(connection);
try {
return sc.get(fileName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void execCmd(String cmd) {
Session session = null;
try {
session = connection.openSession();
// 建立虚拟终端
session.requestPTY("bash");
// 打开一个Shell
session.startShell();
PrintWriter out = new PrintWriter(session.getStdin());
// 准备输入命令
out.println(cmd);
// 输入待执行命令
//读取结果
out.println("exit");
// 关闭输入流
out.close();
// 等待,除非1.连接关闭;2.输出数据传送完毕;3.进程状态为退出;4.超时
session.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, 30000);
} catch (Exception e) {
e.printStackTrace();
System.err.println("出错");
} finally {
if (Objects.nonNull(session)) {
session.close();
}
}
}
public void putFile(File localFile,
String remoteTargetDirectory) {
putFile(localFile.getAbsolutePath(), remoteTargetDirectory);
}
public void putFile(String localFile,
String remoteTargetDirectory) {
try {
execCmd("mkdir -p " + remoteTargetDirectory);
SCPClient scpClient = connection.createSCPClient();
File file = new File(localFile);
SCPOutputStream outputStream = scpClient.put(file.getName(), file.length(), remoteTargetDirectory, null);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
outputStream.write(bytes);
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public boolean login() {
//创建远程连接,默认连接端口为22,如果不使用默认,可以使用方法
//new Connection(ip, port)创建对象
Connection conn = new Connection(ip);
try {
//连接远程服务器
conn.connect();
//使用用户名和密码登录
connection = conn;
return conn.authenticateWithPassword(usr, psword);
} catch (IOException e) {
System.err.printf("用户%s密码%s登录服务器%s失败!", usr, psword, ip);
e.printStackTrace();
}
return false;
}
public String exec(String cmd) throws Exception {
String returnValue = "";
try {
//打开一个会话
Session session = connection.openSession();
//执行命令,多条命令分号隔开
session.execCommand(cmd);
returnValue = processStdout(session.getStdout());
} catch (IOException e) {
e.printStackTrace();
throw new Exception("执行命令 " + StrUtil.join(";", cmd) + " 失败。");
}
return returnValue;
}
private String processStdout(InputStream in) {
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, "utf8"));
String line;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
运行完成以后会需要把新建的.service文件手动复制到ubuntu存放自动启动service文件目录 ,在控制台会打印复制命令,按照控制台的命令进行输入即可