项目模块-备份数据库

引入依赖


    com.jcraft
    jsch
    0.1.55

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 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();
		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 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());
	}

 

你可能感兴趣的:(JAVA)