sshj 示例

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' 
}
posted on 2018-08-29 10:37  开学五年级了 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/qwsdcv/p/9552862.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值