Skip to content

Commit

Permalink
更改命令执行方式为shell,避免因为无法获得环境变量而无法启动程序的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
zhy6599 committed Nov 26, 2019
1 parent 0cbc6e5 commit 1cec669
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 77 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@
import me.zhengjie.modules.mnt.domain.DeployHistory;
import me.zhengjie.modules.mnt.domain.ServerDeploy;
import me.zhengjie.modules.mnt.repository.DeployRepository;
import me.zhengjie.modules.mnt.service.*;
import me.zhengjie.modules.mnt.service.dto.*;
import me.zhengjie.modules.mnt.service.DeployHistoryService;
import me.zhengjie.modules.mnt.service.DeployService;
import me.zhengjie.modules.mnt.service.ServerDeployService;
import me.zhengjie.modules.mnt.service.dto.AppDto;
import me.zhengjie.modules.mnt.service.dto.DeployDto;
import me.zhengjie.modules.mnt.service.dto.DeployQueryCriteria;
import me.zhengjie.modules.mnt.service.dto.ServerDeployDto;
import me.zhengjie.modules.mnt.service.mapper.DeployMapper;
import me.zhengjie.modules.mnt.util.ExecuteShellUtil;
import me.zhengjie.modules.mnt.util.ScpClientUtil;
Expand All @@ -26,9 +31,8 @@
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Set;
Expand All @@ -42,7 +46,7 @@
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeployServiceImpl implements DeployService {

private final String FILE_SEPARATOR = File.separatorChar + "";
private final String FILE_SEPARATOR = "/";

private final DeployRepository deployRepository;

Expand Down Expand Up @@ -163,6 +167,7 @@ private String deployApp(String fileSavePath, Long id) {
boolean result = checkIsRunningStatus(port, executeShellUtil);
sb.append("服务器:").append(deployDTO.getName()).append("<br>应用:").append(app.getName());
sendResultMsg(result, sb);
executeShellUtil.close();
}
return "部署结束";
}
Expand All @@ -178,7 +183,7 @@ private void sleep(int second) {
private void backupApp(ExecuteShellUtil executeShellUtil, String ip, String fileSavePath, String appName, String backupPath, Long id) {
String deployDate = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);
StringBuilder sb = new StringBuilder();
if (!backupPath.endsWith(FILE_SEPARATOR)) {
if (!backupPath.endsWith(FILE_SEPARATOR)&&!backupPath.endsWith("\\")) {
backupPath += FILE_SEPARATOR;
}
backupPath += appName + FILE_SEPARATOR + deployDate + "\n";
Expand Down Expand Up @@ -219,8 +224,8 @@ private void stopApp(int port, ExecuteShellUtil executeShellUtil) {
* @return true 正在运行 false 已经停止
*/
private boolean checkIsRunningStatus(int port, ExecuteShellUtil executeShellUtil) {
String statusResult = executeShellUtil.executeForResult(String.format("fuser -n tcp %d", port));
return !"".equals(statusResult.trim());
String result = executeShellUtil.executeForResult(String.format("fuser -n tcp %d", port));
return result.indexOf("/tcp:")>0;
}

private void sendMsg(String msg, MsgType msgType) {
Expand Down Expand Up @@ -248,16 +253,15 @@ public String serverStatus(Deploy resources) {
sendMsg(sb.toString(), MsgType.ERROR);
}
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}

private boolean checkFile(ExecuteShellUtil executeShellUtil, AppDto appDTO) {
String sb = "find " +
appDTO.getDeployPath() +
" -name " +
appDTO.getName();
return executeShellUtil.executeShell(sb);
StringBuilder sb = new StringBuilder("find ").append(appDTO.getDeployPath()).append(" -name ").append(appDTO.getName());
String result = executeShellUtil.executeForResult(sb.toString());
return result.indexOf("/tcp:")>0;
}

/**
Expand All @@ -282,6 +286,7 @@ public String startServer(Deploy resources) {
boolean result = checkIsRunningStatus(app.getPort(), executeShellUtil);
sendResultMsg(result, sb);
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}
Expand Down Expand Up @@ -312,6 +317,7 @@ public String stopServer(Deploy resources) {
sendMsg(sb.toString(), MsgType.INFO);
}
log.info(sb.toString());
executeShellUtil.close();
}
return "执行完毕";
}
Expand All @@ -320,7 +326,7 @@ public String stopServer(Deploy resources) {
public String serverReduction(DeployHistory resources) {
Long deployId = resources.getDeployId();
Deploy deployInfo = deployRepository.findById(deployId).orElseGet(Deploy::new);
Timestamp deployDate = resources.getDeployDate();
String deployDate = DateUtil.format(resources.getDeployDate(), DatePattern.PURE_DATETIME_PATTERN);
App app = deployInfo.getApp();
if (app == null) {
sendMsg("应用信息不存在:" + resources.getAppName(), MsgType.ERROR);
Expand Down Expand Up @@ -363,6 +369,7 @@ public String serverReduction(DeployHistory resources) {
StringBuilder sb = new StringBuilder();
sb.append("服务器:").append(ip).append("<br>应用:").append(resources.getAppName());
sendResultMsg(result, sb);
executeShellUtil.close();
return "";
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,106 +1,88 @@
package me.zhengjie.modules.mnt.util;

import com.jcraft.jsch.*;
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.*;
import java.util.Vector;

/**
* 执行shell命令
*
* @author: ZhangHouYing
* @date: 2019/8/10
*/
@Slf4j
public class ExecuteShellUtil {

private String ipAddress;

private String username;

private String password;

public final int DEFAULT_SSH_PORT = 22;

private Vector<String> stdout;

public ExecuteShellUtil(final String ipAddress, final String username, final String password) {
this.ipAddress = ipAddress;
this.username = username;
this.password = password;
stdout = new Vector<String>();
}
Session session;

public int execute(final String command) {
int returnCode = 0;
JSch jsch = new JSch();
public ExecuteShellUtil(final String ipAddress, final String username, final String password) {
try {
Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(30000);

Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
session.connect(3000);
} catch (Exception e) {
e.printStackTrace();
}

channel.setInputStream(null);
BufferedReader input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
}

public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
log.info("The remote command is: " + command);

input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
input.close();

if (channel.isClosed()) {
returnCode = channel.getExitStatus();
}
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}

public boolean executeShell(String command) {
int result = execute(command);
for (String str : stdout) {
log.info(str);
}
if (result == 0) {
return true;
} else {
return false;
public void close(){
if (session != null) {
session.disconnect();
}
}

public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
log.info(str);
}
return sb.toString();
}

/**
* 返回值有三条就代表成功了,2条是没启动,多余三条代表脚本有问题
* @param command
* @return
*/
public int checkAppStatus(String command) {
execute(command);
for (String str : stdout) {
log.info(str);
}
return stdout.size();
}

}
6 changes: 3 additions & 3 deletions sql/eladmin-mnt.sql
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@

-- ----------------------------
-- Records of menu
-- ----------------------------

INSERT INTO `menu` VALUES (80, b'0', '服务监控', 'monitor/server/index', 6, 14, 'codeConsole', 'server', b'0', b'0', 'ServerMonitor', '2019-11-07 13:06:39', 'server:list', 1);
INSERT INTO `menu` VALUES (83, b'0', '图表库', 'components/Echarts', 10, 50, 'chart', 'echarts', b'1', b'0', 'Echarts', '2019-11-21 09:04:32', '', 1);
INSERT INTO `menu` VALUES (90, b'0', '运维管理', '', 0, 20, 'mnt', 'mnt', b'0', b'0', 'Mnt', '2019-11-09 10:31:08', NULL, 1);
Expand Down Expand Up @@ -46,7 +46,7 @@ CREATE TABLE `mnt_app` (
-- ----------------------------
-- Records of mnt_app
-- ----------------------------
INSERT INTO `mnt_app` VALUES (1, 'eladmin-monitor-2.3.jar', '/opt/upload', '/opt/monitor', '/opt/backup', 8777, 'cd /opt/monitor/\nnohup java -jar eladmin-monitor-2.2.jar >nohup.out 2>&1 &\n', 'mv /opt/upload/eladmin-monitor-2.2.jar /opt/monitor/\ncd /opt/monitor\nnohup java -jar eladmin-monitor-2.2.jar >nohup.out 2>&1 &\n', '2019-11-24 20:52:59');
INSERT INTO `mnt_app` VALUES (1, 'eladmin-monitor-2.3.jar', '/opt/upload', '/opt/monitor', '/opt/backup', 8777, 'cd /opt/monitor\nnohup java -jar eladmin-monitor-2.3.jar >nohup.out 2>&1 &\n', 'mkdir -p /opt/monitor\nmv -f /opt/upload/eladmin-monitor-2.3.jar /opt/monitor\n', '2019-11-24 20:52:59');

-- ----------------------------
-- Table structure for mnt_database
Expand Down
2 changes: 1 addition & 1 deletion sql/eladmin.sql
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ CREATE TABLE `mnt_app` (
-- ----------------------------
-- Records of mnt_app
-- ----------------------------
INSERT INTO `mnt_app` VALUES (1, 'eladmin-monitor-2.3.jar', '/opt/upload', '/opt/monitor', '/opt/backup', 8777, 'cd /opt/monitor/\nnohup java -jar eladmin-monitor-2.2.jar >nohup.out 2>&1 &\n', 'mv /opt/upload/eladmin-monitor-2.2.jar /opt/monitor/\ncd /opt/monitor\nnohup java -jar eladmin-monitor-2.2.jar >nohup.out 2>&1 &\n', '2019-11-24 20:52:59');
INSERT INTO `mnt_app` VALUES (1, 'eladmin-monitor-2.3.jar', '/opt/upload', '/opt/monitor', '/opt/backup', 8777, 'cd /opt/monitor\nnohup java -jar eladmin-monitor-2.3.jar >nohup.out 2>&1 &\n', 'mkdir -p /opt/monitor\nmv -f /opt/upload/eladmin-monitor-2.3.jar /opt/monitor\n', '2019-11-24 20:52:59');

-- ----------------------------
-- Table structure for mnt_database
Expand Down

0 comments on commit 1cec669

Please sign in to comment.