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 projectrepositories { // 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 阅读( ...) 评论( ...) 收藏