引入依賴
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
ExecuteShellUtil工具類
package me.zhengjie.modules.mnt.util;
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.*;
import java.util.Vector;
/**
* 執行shell命令
*/
@Slf4j
public class ExecuteShellUtil {
private Vector<String> stdout;
Session session;
public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
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();
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);
}
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
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);
}
return sb.toString();
}
}
Controller
@PostMapping
@ApiOperation(value = "數據庫備份")
public ResponseEntityT<YDatabaseBackupDto> create(@Validated @RequestBody YDatabaseBackupAdd resources){
String date = DateUtils.getNewDate().getTime() + "";
deployService.getBackupDatabase(resources.getBackupName(),date);
return new ResponseEntityT<>(yDatabaseBackupService.create(resources,date),HttpStatus.CREATED);
}
DeployServiceImpl
@Override
public String getBackupDatabase(String backup,String date) {
ExecuteShellUtil executeShellUtil = getExecuteShellUtil(ip);
//username 數據庫名稱
//password 數據庫密碼
//backupSQLUrl 備份文件存放地址
final String sql = " mysqldump -u"+ username +" -p" + password + " --all-databases | gzip > " + backupSQLUrl + "" + backup +"_" + date + ".sql.gz";
executeShellUtil.execute(sql);
return "執行完畢";
}
/**
* 查詢服務器信息,服務器信息加密存放數據庫
* @param ip 服務器ip
* @return
*/
private ExecuteShellUtil getExecuteShellUtil(String ip) {
ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip);
if (serverDeployDTO == null) {
sendMsg("IP對應服務器信息不存在:" + ip, MsgType.ERROR);
throw new BadRequestException("IP對應服務器信息不存在:" + ip);
}
return new ExecuteShellUtil(ip, serverDeployDTO.getAccount(), serverDeployDTO.getPassword(),serverDeployDTO.getPort());
}