Java 连接linux服务器
Java 连接linux服务器
转载请标明出处^_^
原文首发于: www.zhangruibin.com
本文出自于: RebornChang的博客
众所周知,linux服务器是支持ssh命令连接的,连接格式:ssh user@ipAddr port,回车之后输入密码即可连接。
那么,怎样使用Java代码进行连接,并且执行命令呢?
来了解一下什么是Jsch与ganymed-ssh2
Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。MVN地址为:https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2
可以看到最后的更新日志为2014年。
ganymed-ssh2和Jsch大同小异,不再多说,重点说下怎样在Java代码中连接linux。
首先确认linux开启了ssh连接方式
centos7下执行命令:
ps -e | grep sshd
若输出为:
1132 ? 00:00:00 sshd
10614 ? 00:00:02 sshd
10616 ? 00:00:00 sshd
10748 ? 00:00:00 sshd
则证明开启了ssh服务,若没有以上输出,则需要开启ssh服务,开启方法:
开启方法
使用shell工具测试连接
使用Xshell,secureCRT,FinallShell等工具进行连接测试。
命令格式:ssh user@ipAddr port。
测试效果如下图:
主机上编写一个shell脚本用于测试
在主机上编写一个简单的shell脚本用于测试。
脚本名称为: testForJava ;
脚本目录为:/test/shell;
脚本内容:
#!/bin/sh
echo "If you can read this ,it means that you can conctrl server remote!"
编辑完之后再服务器上本地测试效果如下图所示:
Maven项目引入依赖编写Java代码测试
这里说下maven的,非maven项目网上下载jar包引入。
ganymed-ssh2的maven地址上文中已经说过了,在POM文件中加入相关依赖就行了,博文中加入的依赖为:
<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
Java代码为:
public class TestUseSSH {
private static String ip = "your ip";
private static int port = 22;
private static String user = "user";
private static String pswd = "pswd";
public static void main(String[] args) {
try {
Connection conn = new Connection(ip,port);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(user,
pswd);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
Session sess = conn.openSession();
sess.execCommand("sh /test/shell/testForJava");
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(System.err);
System.exit(2);
}
}
}
运行后输出结果为:
If you can read this ,it means that you can conctrl server remote!
注:这里只说了linux下执行命令,更多功能在这里没有描述,有兴趣的可以自行深入探索,Over!
还没有评论,来说两句吧...