sshj 示例

sshj 示例

開發經常須要去服務器作一些操做,好比配置一下,或者取服務器的配置什麼的,須要寫點工具方便開發。java

下面是一個使用sshj 模擬ssh的過程。tomcat

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' 
}
相關文章
相關標籤/搜索