zoukankan      html  css  js  c++  java
  • 秘钥登录服务器执行shell脚本

    做自动化的时候,有时候避免不了要和服务器有互动,刚巧碰上一个项目,需要执行命令才能完成本次测试。

    昨天遇到的是秘钥形式的,只有秘钥和用户名,百度找了许久也没有思路,(能账号密码登录服务器的还简单些),后来看到一篇博文,受到启发,把他的代码改了又改,结果还真行了

    代码如下:

    import com.jcraft.jsch.*;
    import org.slf4j.LoggerFactory;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.nio.charset.Charset;
    import java.util.Properties;
    
    /**
     * @author 
     *    秘钥形式登录服务器执行shell脚本操作
     */
    public class ExecuteShellWithKey {
    
        /**
         * slf4j
         */
    
        private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ExecuteShellWithKey.class);
        private Session session;
    
        /**
         * 远程连接Linux 服务器 执行相关的命令
         *
         * @param keyFile    秘钥文件
         * @param userName   用户名
         * @param passphrase 重置后密码
         * @param host       主机ip
         * @param cmd        执行shell调用命令
         * @throws JSchException
         * @throws IOException
         */
        private void runShell(String keyFile, String userName, String passphrase, String host, String cmd) {
            if (!connect(keyFile, userName, passphrase, host)) {
                return;
            }
            ChannelExec channelExec = null;
            BufferedReader reader = null;
            try {
                channelExec = (ChannelExec) session.openChannel("exec");
                channelExec.setCommand(cmd);
                channelExec.setInputStream(null);
                channelExec.setErrStream(System.err);
                channelExec.connect();
                InputStream in = channelExec.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
                String buf = null;
                StringBuffer sb = new StringBuffer();
                while ((buf = reader.readLine()) != null) {
                    sb.append(buf);
                    // 输出每个命令执行后,返回数据
                    logger.info(sb.toString());
                }
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (channelExec != null) {
                    channelExec.disconnect();
                }
                if (null != session) {
                    session.disconnect();
                }
            }
        }
    
        /**
         * 连接到指定的HOST
         *
         * @param keyFile
         * @param userName
         * @param passphrase
         * @param host
         * @throws JSchException
         */
        private boolean connect(String keyFile, String userName, String passphrase, String host) {
            // 创建JSch对象
            JSch jsch = new JSch();
            try {
                // 引入秘钥文件       
                jsch.addIdentity(keyFile);
                // 根据用户名,主机ip,端口获取一个Session对象
                session = jsch.getSession(userName, host, 22);
                UserInfo ui = new MyUserInfo(passphrase);
                session.setUserInfo(ui);
                // 设置密码
                session.setPassword(passphrase);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                // 为Session对象设置properties
                session.setConfig(config);
                int timeout = 60000000;
                // 设置timeout时间
                session.setTimeout(timeout);
                // 通过Session建立链接
                session.connect();
            } catch (JSchException e) {
                e.printStackTrace();
                logger.error("connect error !");
                return false;
            }
            return true;
        }
    
        public class MyUserInfo implements UserInfo {
            private String passphrase = null;
    
            public MyUserInfo(String passphrase) {
                this.passphrase = passphrase;
            }
    
            public String getPassphrase() {
                return passphrase;
            }
    
            public String getPassword() {
                return null;
            }
    
            public boolean promptPassphrase(String s) {
                return true;
            }
    
            public boolean promptPassword(String s) {
                return true;
            }
    
            public boolean promptYesNo(String s) {
                return true;
            }
    
            public void showMessage(String s) {
                logger.info(s);
            }
        }
    }

    要是觉得对你有帮助,并且解决了你的问题,麻烦请高抬你发财的贵手,在评论给我个赞即可。。。

  • 相关阅读:
    Jenkins自动化多项目编译和Tomcat部署懒人终极大招
    python 装饰器总结
    selenium3之-测试环境搭建
    centos7.4 安装ftp服务器并配置匿名用户权限
    selenium3之-运行原理
    flutter 打包apk
    Fluwx:微信SDK在Flutter上的实现
    flutter 购物车功能
    flutter sharesdk实现跨平台分享
    Web API接口设计经验总结
  • 原文地址:https://www.cnblogs.com/longronglang/p/8192190.html
Copyright © 2011-2022 走看看