码迷,mamicode.com
首页 > 其他好文 > 详细

sshj 示例

时间:2018-08-29 14:52:41      阅读:2317      评论:0      收藏:0      [点我收藏+]

标签:imp   oid   section   read   word   UNC   channel   with   stat   

sshj 示例

开发常常需要去服务器做一些操作,比如配置一下,或者取服务器的配置什么的,需要写点工具方便开发。

下面是一个使用sshj 模拟ssh的过程。

package sshStuff;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

public class Functor {

    public static void main(String[] args) throws Exception {
        String TMP = "http://10.59.60.231:31154";
        if(args.length >= 1){
            TMP = args[0];
        }
        String ret = connect(TMP);
        System.out.println(ret);
    }

    public static String connect(String url) throws Exception {
        SSHClient ssh = new SSHClient();
        ssh.addHostKeyVerifier(new PromiscuousVerifier());
        ssh.connect(getIp(url), getPort(url));
        ssh.authPassword("root", "123456");

        Session session = ssh.startSession();
        Command cmd = session.exec("cat /usr/local/tomcat/StartTomcat.sh");
        String ret = IOUtils.readFully(cmd.getInputStream()).toString();
        // System.out.println(ret);
        session.close();
        ssh.close();
        return ret;
    }

    private static String getIpPort(String url) {

        String[] slash = url.split("/");
        String ipport = null;
        if (url.toLowerCase().startsWith("http")) {
            ipport = slash[2];
        } else {
            ipport = slash[0];
        }
        return ipport;
    }

    private static String getIp(String url) {
        String ipport = getIpPort(url);
        return ipport.split(":")[0];
    }

    private static int getPort(String url) {
        String ipport = getIpPort(url);
        return Integer.parseInt(ipport.split(":")[1]) + 1;
    }

}

下面是gradle配置

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
   
    compile group: 'net.schmizz', name: 'sshj', version: '0.10.0'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}


jar {
    from {configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    manifest {
        attributes 'Main-Class': 'sshStuff.Functor'
    }
    exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA' 
}

sshj 示例

标签:imp   oid   section   read   word   UNC   channel   with   stat   

原文地址:https://www.cnblogs.com/qwsdcv/p/9552862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!