我们有时候会用到利用远程服务器,java代码怎么链接到远程服务器上呢,这里我们做下简单的封装。
首先安装依赖包。
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
安装完毕,我们先来简单的封装下。
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class SshTools {
public static String username="root";
public static String password="你远程登录的密码";
public static String ip="远程服务器的地址";
public static String port=22;
public static void ssh_tool(String cmd){
try{
Connection conn= new Connection(ip,port);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if(isAuthenticated ==false)
{
// System.out.println("--------");
throw new IOException("Authorication failed");
}
Session sess = conn.openSession();
sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while(true)
{
String line = br.readLine();
if(line==null) break;
System.out.println(line);
}
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SshTools sshTools=new SshTools();
sshTools.ssh_tool("ifconfig");
}
}
这里封装完毕,我们先来执行下。
这样我们就完成来一个简单的封装,我们去改造下,对应的代码。
public class SshTools {
public static String username = "root";
public static String password = "你的密码";
public static String ip = "";
public static Integer port = 22;
private Session ssh(String username, String password, String ip, Integer port) {
//建立链接
Connection conn = new Connection(ip, port);
try {
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
throw new IOException("Authorication failed");
}
Session sess = conn.openSession();
return sess;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
//执行命令
public String ssh_tool(String cmd) {
try {
Session session = this.ssh(username, password, ip, port);
session.execCommand(cmd);
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
String reslut = "";
while (true) {
String line = br.readLine();
if (line == null) break;
reslut += line;
}
session.close();
return reslut;
} catch (IOException e) {
return null;
}
}
}
这里返回结果,后续还需要很多的优化,根据我们的实际项目会对这里面的操作进行优化,这里只是大概的封装下,远程是怎么操作的,给大家提供一些方法而已。
我现在这些分享的都是我在实际中会用的,后续可能会出一系列的分享,现在的分享就是一些日常工作和学习中的一些总结,无论是遇到的坑,还是在工作中,遇到的难题怎么解决的,都会在公众号持续分享。
后续的分享可能会更加专注测试相关,大家有什么想了解,也可以在粉丝群或者后台私聊我。都可以,我会给大家持续分享一些技术方面的东西。希望能和大家有一个更好,更加良性的互动。加粉丝群可以参考。组建雷子说测试粉丝交流群通知。