美文网首页
[java] ganymed-ssh2 远程执行shell脚本

[java] ganymed-ssh2 远程执行shell脚本

作者: 炒面Z | 来源:发表于2020-04-30 11:47 被阅读0次

需求场景:

用户微信三方平台授权通过后,需要上传微信业务文件至nginx前端服务器中

image.png

后台实现方案:

1.客户登录微信公众平台,下载业务文件 如:MP_verify_xxx.txt
2.上传业务文件时,后台先把业务文件上传至阿里云OSS,拿到文件URL
3.服务端(java)使用 ganymed-ssh2 插件远程执行shell脚本(wget URL)命令把文件拷贝至nginx前端服务器中

shell脚本

远程下载文件至特定文件夹且重命名(会覆盖同名文件)
cd /opt/nginx80/web/MP_verify/ && sudo wget https://test.oss-cn-hangzhou.aliyuncs.com/mpverify/MP_verify_xxx.txt -O MP_verify_xxx.txt

ganymed-ssh2 pom文件

        <!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
        <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>262</version>
        </dependency>

代码1 - linux服务器为账号密码登录

/**
     * java ssh账号密码远程登录,执行shell脚本
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String hostName = "ip地址";
        String userName = "用户名";
        String password = "密码";

        //第1步:连接服务器
        Connection conn = new Connection(hostName);
        conn.connect();

        //第2步:账号密码登录
        boolean isAuthenticated = conn.authenticateWithPassword(userName, password);
        if (!isAuthenticated) {
            throw new IOException("Authentication failed.");
        }

        Session sess = conn.openSession();

        //第3步: 执行shell脚本-> 下载文件至特定文件夹且重命名 (重复文件覆盖)
        sess.execCommand("cd /opt/nginx80/web/MP_verify/ && sudo wget https://test.oss-cn-hangzhou.aliyuncs.com/mpverify/MP_verify_xxx.txt -O MP_verify_xxx.txt");

        //第4步: 打印脚本返回结果
        String result = processStdout(sess.getStdout(), "UTF-8");
        log.info("shell脚本返回:[{}]", result.toString());

        // 最后关闭资源
        conn.close();
        sess.close();
    }

    /**
     * 解析脚本执行返回的结果集
     *
     * @param in      输入流对象
     * @param charset 编码
     * @return 以纯文本的格式返回
     * @since V0.1
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

代码2 - linux服务器为密钥登录

/**
     * java ssh密钥远程登录,执行shell脚本
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        String hostName = "ip地址";
        String userName = "账号";
        String password = "";
        String rsaPem = "-----BEGIN RSA PRIVATE KEY-----\n" +
                "MIIEpQIBAAKCAQEAxCe4c1RlITHaAJKBkZbEuscL8gz8v5kg0gRs5bqVcQb3Patg\n" +
                "ldeydzTr8/93yBOUssE0AANFhdkDKcogW6z2aHu3oFkX1PzzdJO35W8=\n" +
                "-----END RSA PRIVATE KEY-----";

        // 也可以从文件读取密钥
        // File privateKey = ResourceUtils.getFile("classpath:key/hexiang-online.pem");
        // String rsaPem = FileUtils.readFileToString(privateKey, Charset.defaultCharset());

        //第1步:连接Linux服务器
        Connection conn = new Connection(hostName);
        conn.connect();

        //第2步:密钥登录
        boolean isAuthenticated = conn.authenticateWithPublicKey(userName, rsaPem.toCharArray(), password);
        if (!isAuthenticated) {
            throw new IOException("Authentication failed.");
        }
        //第3步:执行shell命令
        Session sess = conn.openSession();
        sess.execCommand("cd /opt/nginx80/web/MP_verify/ && sudo wget https://test.oss-cn-hangzhou.aliyuncs.com/mpverify/MP_verify_xxx.txt -O MP_verify_xxx.txt");

        //第4步: 打印脚本返回结果
        StringBuffer details = new StringBuffer();
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null) {
                break;
            }
            details.append(line + "\r\n");//换行
        }
        log.info("shell脚本返回:[{}]", details.toString());

        // 最后关闭资源
        conn.close();
        sess.close();
    }

如果从pem文件读取密钥的话

        // 也可以从文件读取密钥
        File privateKey = ResourceUtils.getFile("classpath:key/hexiang-online.pem");
        String rsaPem = FileUtils.readFileToString(privateKey, Charset.defaultCharset());

相关文章

网友评论

      本文标题:[java] ganymed-ssh2 远程执行shell脚本

      本文链接:https://www.haomeiwen.com/subject/qchzwhtx.html