百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

Java ssh实现远程服务器部署(java远程登录服务器)

toqiye 2024-09-04 20:06 3 浏览 0 评论

pom依赖

        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>


BtpAbstractService类

/**
 * <p>Title: abstract service</p>
 * <p>Author: lehoon</p>
 * <p>Date: 2022/2/28 16:48</p>
 */
@Slf4j
public abstract class BtpAbstractService {
    protected String deployPath;
    protected String deployBasePath;
    //service operate request
    protected BtpDeployServiceBaseEntity serviceBaseEntity;

    public BtpAbstractService(BtpDeployServiceBaseEntity serviceBaseEntity) {
        this.serviceBaseEntity = serviceBaseEntity;
    }

    protected boolean isDeployBasePathEnvEmpty() {
        deployBasePath = StringUtils.trimToEmpty(getDeployBasePath());
        return StringUtils.isBlank(deployBasePath);
    }

    protected String getDeployBasePath() {
        return getEnvByName(BtpDeployNodeEnvType.BTP_DEPLOY_NODE_ENV_TYPE_DEPLOY_HOMEPATH.getValue());
    }

    protected String getEnvByName(String name) {
        if (serviceBaseEntity == null || CollectionUtil.isEmpty(serviceBaseEntity.getEnvMap())) return null;
        if (serviceBaseEntity.getEnvMap().containsKey(name)) return serviceBaseEntity.getEnvMap().get(name).getEnvValue();
        return null;
    }

    protected void updateDeployPath() {
        deployPath = String.format("%s/%s", fixFsFilePath(deployBasePath), serviceBaseEntity.getServiceId());
    }

    protected boolean checkNodeNetState() {
        return TcpHelper.isRemoteAlive(serviceBaseEntity.getNodeHost(), serviceBaseEntity.getNodePort());
    }

    protected String shellDisableEchoCmd() {
        return " >> /dev/null 2>&1";
    }

    protected void sleepCmd() {
        sleep(500);
    }

    protected void sleep3() {
        sleep(2000);
    }

    protected void sleep5() {
        sleep(5000);
    }

    protected void sleep(int timeout) {
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
        }
    }

    protected String fixFsFilePath(String path) {
        if (path == null || path.length() == 0) return "";
        if (!path.endsWith("/")) return path;
        return path.substring(0, path.length() - 1);
    }

    protected boolean isDeployBasePathValid() {
        return deployBasePath != null && deployBasePath.startsWith("/");
    }


    abstract protected void preCheck() throws BtpDeployException;
    abstract protected void nextCheck() throws BtpDeployException;
    abstract protected void process() throws BtpDeployException;
    abstract protected void rollBack() throws BtpDeployException;
}


BtpAbstractSSHService类

/**
 * <p>Title: ssh 操作</p>
 * <p>Description: </p>
 * <p>Author: lehoon</p>
 * <p>Date: 2022/1/20 15:38</p>
 */
@Slf4j
public abstract class BtpAbstractSSHService extends BtpAbstractService {
    //ssh connection
    protected Connection connection = null;

    public BtpAbstractSSHService(BtpDeployServiceBaseEntity serviceBaseEntity) {
        super(serviceBaseEntity);
    }

    public void service() throws BtpDeployException {
        preCheck();

        try {
            login(1000);
        } catch (BtpDeployException e) {
            log.error("登陆远程服务器失败. ", e);
            throw e;
        }

        try {
            nextCheck();
            sleep3();
            process();
            disConnect();
        } catch (BtpDeployException e) {
            log.error("部署服务操作失败, 错误信息,", e);
            rollBack();
            disConnect();
            throw e;
        } finally {
            disConnect();
        }
    }

    public void disConnect() {
        if (connection == null) return;
        connection.close();
        connection = null;
    }

    /**
     * 登陆远程服务器
     * @param timeout
     * @throws Exception
     */
    public void login(int timeout) throws BtpDeployException {
        connection = new Connection(serviceBaseEntity.getNodeHost(), serviceBaseEntity.getNodePort());
        try {
            connection.connect(null, timeout, 0);
            boolean isAuthenticate = connection.authenticateWithPassword(serviceBaseEntity.getUserName(), serviceBaseEntity.getPassword());
            if (!isAuthenticate) {
                throw new BtpDeployException("用户名密码错误,登陆失败");
            }
        } catch (IOException e) {
            log.error("登陆远程服务器失败,", e);
            if (e.getCause().getMessage().indexOf("method password not supported") != -1) {
                throw new BtpDeployException("远程服务器不支持密码认证, 请修改ssh配置文件");
            }

            throw new BtpDeployException("登陆远程服务器失败, 请检查原因");
        } catch (Exception e){
            throw new BtpDeployException("登陆远程服务器失败, 请检查原因");
        }
    }

    private void checkConnectState() throws IOException {
        if (connection == null) throw new IOException("未与服务器建立连接, 不能执行命令.");
        if (!connection.isAuthenticationComplete()) throw new IOException("与服务器连接认证未通过, 不能执行命令.");
    }

    private String readCmdResult(InputStream inputStream) {
        StringBuilder result = new StringBuilder(1024);

        try {
            InputStream stdout = new StreamGobbler(inputStream);
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String cmdResLine = null;

            while (true) {
                cmdResLine = br.readLine();
                if (cmdResLine == null) {
                    break;
                }
                result.append(cmdResLine);
            }
        } catch (IOException e) {
            log.error("读取远程服务器shell指令结果失败, ", e);
        }

        return result.toString();
    }

    public boolean executeCmd(String cmd) throws BtpDeploySSHExecException {
        try {
            return execute1(cmd);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BtpDeploySSHExecException(e.getMessage());
        }
    }

    private Session openSession() throws Exception {
        checkConnectState();

        try {
            return connection.openSession();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new Exception("打开终端执行环境会话失败,执行命令失败.");
        }
    }

    /**
     * 执行命令
     * @param cmd
     * @return
     * @throws IOException
     */
    public String execute(String cmd) throws Exception {
        sleepCmd();
        Session session = openSession();
        preHandleSession(session);
        session.execCommand(cmd);
        String result = readCmdResult(session.getStdout());
        log.info("执行命令execute[{}],返回结果为[{}]",  cmd, result);
        session.close();
        return result;
    }

    public boolean execute1(String cmd) throws Exception {
        sleepCmd();
        Session session = openSession();
        preHandleSession(session);
        session.execCommand(cmd);
        String result = readCmdResult(session.getStdout());
        log.info("执行命令execute1[{}],返回结果为[{}]", cmd, result);
        int code = 0;
        try {
            code = session.getExitStatus();
            log.info("执行命令execute1[{}],操作码为[{}],返回结果为[{}]", cmd, code, result);
        } catch (Exception e) {
            log.error("执行命令出错", e.fillInStackTrace());
        } finally {
            if (session != null) session.close();
        }
        return code == 0;
    }

    /**
     * 创建目录
     * @param dir
     * @return
     */
    public String mkdir(String dir) throws BtpDeploySSHExecException {
        String cmd = String.format("mkdir -p %s", dir);
        try {
            return execute(cmd);
        } catch (Exception e) {
            log.error("创建目录失败,", e);
            throw new BtpDeploySSHExecException(e.getMessage());
        }
    }

    public boolean mkdir1(String dir) throws BtpDeploySSHExecException {
        String cmd = String.format("mkdir -p %s", dir);
        return executeCmd(cmd);
    }

    public boolean createDirectory(String directory) throws BtpDeploySSHExecException{
        return mkdir1(directory);
    }

    /**
     * 解压zip文件到指定目录
     * @param zipSrc
     * @param distDir
     * @return
     */
    public boolean unzip(String zipSrc, String distDir) throws BtpDeploySSHExecException {
        String cmd = String.format("unzip -oq %s -d %s", zipSrc, distDir);
        return executeCmd(cmd);
    }

    /**
     * 修改文件内容
     * @param src
     * @param dist
     * @param filePath
     * @return
     * @throws Exception
     */
    public String replaceInFile(String src, String dist, String filePath) throws BtpDeploySSHExecException {
        String cmd = String.format("sed -i 's/%s/%s/' %s", src, dist, filePath);
        try {
            return execute(cmd);
        } catch (Exception e) {
            log.error("修改文件内容失败", e);
            throw new BtpDeploySSHExecException();
        }
    }

    public boolean rmdir(String filePath) throws BtpDeploySSHExecException {
        if (filePath == null || filePath.length() == 0) return false;
        for (String path : SAFE_DELETE_FILESYSTEM_PATH_DEFAULT) {
            if (path.equalsIgnoreCase(filePath)) throw new BtpDeploySSHExecException(String.format("目录[%s]不允许删除", filePath));
        }

        String cmd = String.format("rm -rf %s", filePath);
        return executeCmd(cmd);
    }

    protected boolean deleteDirectory(String directory) throws BtpDeploySSHExecException {
        if (directory == null || directory.length() == 0 || "/".equalsIgnoreCase(directory)) return true;
        String cmd = String.format("rm -rf %s", directory);
        return executeCmd(cmd);
    }

    /**
     * 删除文件
     * @return
     * @throws IOException
     */
    protected boolean deleteFile(String filePath) throws BtpDeploySSHExecException {
        if (filePath == null || filePath.length() == 0 || "/".equalsIgnoreCase(filePath)) return true;
        String cmd = String.format("rm -rf %s", filePath);
        return executeCmd(cmd);
    }

    protected boolean deleteFile1(String filePath) {
        try {
            return deleteFile(filePath);
        } catch (BtpDeploySSHExecException e) {
            return false;
        }
    }

    /**
     * 文件拷贝:war包+策略zip文件
     * src=路径+文件名;des=目的路径
     *
     * */
    public void copyDoucment(String src, String des)
            throws BtpDeploySSHExecException {
        if (connection == null) throw new BtpDeploySSHExecException("未与服务器建立连接, 不能执行上传文件命令.");
        try {
            SCPClient scpClient = connection.createSCPClient();
            scpClient.put(src, des);
        } catch (IOException e) {
            log.error("上传文件到远程服务器失败,", e);
            throw new BtpDeploySSHExecException();
        }
    }

    /**
     * 进入指定目录并返回目录名称
     * @param basePath
     * @return
     * @throws IOException
     */
    public String cmdPwd(String basePath) throws BtpDeploySSHExecException {
        String cmd = String.format("cd %s && pwd", basePath);
        try {
            return execute(cmd);
        } catch (Exception e) {
            log.error(String.format("切换文件目录失败,目录[%s]不存在", basePath), e);
            throw new BtpDeploySSHExecException();
        }
    }

    public String moveFile(String oldPath, String newPath) throws BtpDeploySSHExecException {
        String cmd = String.format("mv %s %s", oldPath, newPath);
        try {
            return execute(cmd);
        } catch (Exception e) {
            log.error(String.format("移动文件失败,原文件[%s]目标目录[%s]不存在", oldPath, newPath), e);
            throw new BtpDeploySSHExecException();
        }
    }

    public String lsCmd(String filePath) throws BtpDeploySSHExecException {
        String cmd = String.format("ls %s", filePath);
        try {
            return execute(cmd);
        } catch (Exception e) {
            log.error(String.format("获取文件路径失败,文件[%s]不存在", filePath), e);
            throw new BtpDeploySSHExecException();
        }
    }

    public boolean checkFileExist(String filePath) throws BtpDeploySSHExecException {
        String checkFilePath = lsCmd(filePath);

        if (filePath.equalsIgnoreCase(checkFilePath)) {
            return true;
        }

        return false;
    }


    /**
     * 上传文件到远程服务器
     * @param localFileName
     * @param remotePath
     * @param remoteFileName
     * @throws IOException
     */
    public void uploadFileToRemote(String localFileName, String remotePath, String remoteFileName)
            throws BtpDeploySSHExecException {
        if (connection == null) throw new BtpDeploySSHExecException("未与服务器建立连接, 不能执行上传文件命令.");

        try {
            SCPClient scpClient = connection.createSCPClient();// 建立SCP客户端:就是为了安全远程传输文件
            scpClient.put(localFileName, remoteFileName, remotePath, "0600");
        } catch (IOException e) {
            log.error("上传文件到远程服务器失败,", e);
            throw new BtpDeploySSHExecException();
        }
    }

    public boolean uploadFile2Remote(String localFileName, String remotePath, String remoteFileName) {
        try {
            uploadFileToRemote(localFileName, remotePath, remoteFileName);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    protected boolean checkDeployBasePathExist() throws BtpDeploySSHExecException {
        String tempPathPwd = cmdPwd(deployBasePath);

        if (StringUtils.isBlank(tempPathPwd)) {
            log.info("远程服务器上部署根目录在远程服务器上不存在, {}", deployBasePath);
            return false;
        }

        deployBasePath = tempPathPwd;
        return true;
    }

    protected boolean checkDeployPathExist() throws BtpDeploySSHExecException {
        String tempPathPwd = cmdPwd(deployPath);

        if (StringUtils.isBlank(tempPathPwd)) {
            log.info("远程服务器上部署目录在远程服务器上不存在{}", deployPath);
            return false;
        }

        deployPath = tempPathPwd;
        return true;
    }

    protected boolean dos2unix(String filePath) throws BtpDeploySSHExecException {
        if (filePath == null || filePath.length() == 0) return false;
        String cmd = String.format("dos2unix %s", filePath);
        return executeCmd(cmd);
    }

    protected String getFileName(String filename) {
        if (filename == null || filename.length() == 0) return null;
        return filename.substring(0, filename.lastIndexOf("."));
    }

    private void preHandleSession(Session session) throws IOException {
        session.requestPTY("vt100");
    }

    private static List<String> SAFE_DELETE_FILESYSTEM_PATH_DEFAULT
            = new ArrayList<String>(16);

    static {
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/");
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/boot");
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/home");
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/opt");
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/usr");
        SAFE_DELETE_FILESYSTEM_PATH_DEFAULT.add("/etc");
    }
}


具体操作类通过实现BtpAbastractSSHApamaService类即可

相关推荐

暗网是什么?到底有多可怕?(暗网有多可怕)

https://mp.weixin.qq.com/s/O7l4rveLnXLt-XE2A0WZ3g

“暗网”是什么,到底有多可怕,互联网的“另外一个世界”

来源成戈科技说悄悄告诉你何为“暗网”,暗网的用途是什么?到底多可怕?暗网的英文是“deepnet或deepweb”,也就是深网的意思,我们都知道,南北极的冰川看起来非常雄伟,但是你物理稍微懂一点你就...

什么是暗网?暗网有什么用?进来我告诉你

网的英文是“deepnet或deepweb”,也就是深网的意思,我们都知道,南北极的冰川看起来非常雄伟,但是你物理稍微懂一点你就会知道,我们看到的只是冰山的10%,还有90%在水面以下,很容易看出来,...

网工跳槽必备,2022年最新大厂高频技术面试真题整理

2022年金三银四正在进行,很多粉丝问我要网络工程师面试方面的资料,有在学校准备实习的,有已经工作准备跳槽的。我翻看最近的笔记,正好有整理一份今年大厂的面试题分享给大家。可以先说的是,国内的互联网面试...

三天吃透操作系统面试八股文(三天吃透计算机网络八股文)

操作系统的四个特性?并发:同一段时间内多个程序执行(与并行区分,并行指的是同一时刻有多个事件,多处理器系统可以使程序并行执行)...

掌握前端面试八股文,提升个人能力,实战面试必备!

前言:前端面试是每个前端开发者职业发展中的重要环节。掌握一些常见的前端面试题目,不仅能够在面试中表现出色,还能够提升自身的技术能力和知识广度。本文将为你介绍一些实用的前端面试题目,帮助你在面试中脱颖而...

进大厂必备的Java八股文大全(2022最强精简易懂版)

2022年秋招即将来临,很多同学会问Java面试八股文有必要背吗?答案是,必须背,博主是个三本,今年凭借这篇八股文斩获了多个大厂暑期实习offer,相信秋招一定也可以发挥重要作用。你可以讨厌这种模式,...

2022最新软件测试八股文,能不能拿心仪Offer就看你背得怎样了

前言鉴于目前测试就业越来越严峻,内卷也成了测试领域的代名词了。我的一个HR朋友告诉我,由于门槛较低,现在普通测试岗(偏功能)的投递比已经将近100,也就是一个岗位差不多有百分简历投进来。所以现在还想从...

《面试八股文》之Dubbo17卷(面试 八股文)

作者:moon原文:https://mp.weixin.qq.com/s/-kVf5qWqcw-4AJF7LL3uWw前言...

前端面试八股文?不存在的!(2021前端面试问题)

最近刷到一位前端小姐姐海外工作分享的视频,分享了她的求职,面试以及工作生活的感受,了解到海外求职面试的一个过程,其中我们经常聊的...

凭借这份《2022测试八股文》候选者逆袭面试官,offer拿到手软

《2023测试面试八股文》800道软件测试面试真题,高清打印版打包带走,横扫软件测试面试高频问题,涵盖测试理论、Linux、MySQL、Web测试、接口测试、App测试、Python、Selen...

面试常考八股文及算法(一)(八股文的要求)

define和const的区别1.define是预处理指令,用于创建符号常量。`const`是C和C++的关键字,用于创建具有常量值的变量,本质是只读变量。2.`define`在预处理阶...

面试必备(背)--计算机网络八股文系列

1.OSI七层、TCP/IP四层的关系和区别?七层模型,亦称OSI(OpenSystemInterconnection),它是一个七层的、抽象的模型体,不仅包括一系列抽象的术语或概念,也包括...

Java面试一定要坚持背的八股文!错过会很可惜!

很多人对java面试题都嗤之以鼻,认为无法衡量出一个程序员的真实水平。还有一部分原因,也是因为太难背了。那我们到底还要不要背?背!当然要背!但也不是死记硬背。在我们背诵的过程中,就把java的核心知识...

面试问八股文的公司都是垃圾?(八股文负面影响)

做医生的需要有医师资格证,做财务的有CPA证书,做教师的有教师资格证等等,做程序员的从来没听说过面试的时候需要你提供什么证书,既然没有可以证明从业能力的证书,那面试的时候如何来判断候选人的基本能力呢?...

取消回复欢迎 发表评论: