日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

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類即可

分享到:
標簽:Java ssh
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定