一、所需jar包
需要借助Ganymed SSH的jar包: ganymed-ssh2-build210.jar
下载地址: http://www.ganymed.ethz.ch/ssh2/
API详情: http://www.ganymed.ethz.ch/ssh2/javadoc/ch/ethz/ssh2/package-summary.html
二、实现原理
Ganymed SSH-2 java在整个访问过程中担当SSH的客户端,由于Linux系统自带SSH服务,所以可以直接访问Linux系统并执行相关命令,而 Windows系统则需要首先安装SSH服务。
三、Win下SSH服务的安装配置
当远程服务器为Windows系统时, 需要在远程服务器中安装Windows版的SSH服务,比如:freesshd。
freesshd下载地址: http://www.freesshd.com/?ctt=download
freesshd安装与配置:(可以参考:http://www.cnblogs.com/xred/archive/2012/04/21/2461627.html)
1.安装完freesshd后,首选在[Users]下添加用来远程连接的win系统用户,此处采用密码认证的方式,允许使用shell:
2.然后再在【Authentication】下设置允许密码认证方式:
3.到[Server status]下查看SSH服务器状态,确保启动即可。最后点击【确定】即可。
四、java代码实现远程连接服务器并执行命令
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test; import java.io.IOException; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; /* @author: Liu Yuanyuan purpose: test connecting remote computer and execute linux command */ public class TestRemoteConnect { public static void main(String[] args) { String hostname = "192.168.100.50"; int port = 22;//22 usually the default port String username = "root"; String password = "highgo"; //指明连接主机的IP地址 Connection conn = new Connection(hostname,port); Session ssh = null; try { //连接到主机 conn.connect(); //使用用户名和密码校验 boolean isconn = conn.authenticateWithPassword(username, password); if (!isconn) { System.out.println("用户名称或者是密码不正确"); } else { System.out.println("已经连接OK"); //以下是linux的示例 //将本地conf/server_start.sh传输到远程主机的/opt/pg944/目录下 SCPClient clt = conn.createSCPClient(); clt.put("conf/server_start.sh", "/opt/pg944/"); //执行命令 ssh = conn.openSession(); ssh.execCommand("sh /root/hello.sh"); //ssh.execCommand("perl /root/hello.pl"); //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常. //使用多个命令用分号隔开 //ssh.execCommand("cd /root; sh hello.sh"); /* 执行windows系统命令的示例 Session sess = conn.openSession(); sess.execCommand("ipconfig"); */ //将Terminal屏幕上的文字全部打印出来 InputStream is = new StreamGobbler(ssh.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is)); while (true) { String line = brs.readLine(); if (line == null) { break; } System.out.println(line); } } } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { //连接的Session和Connection对象都需要关闭 if(ssh!=null) { ssh.close(); } if(conn!=null) { conn.close(); } } } }
五、其他的实现方式:使用jsch 远程连接linux执行命令(与以上类似,未测试)
jar包下载:http://www.jcraft.com/jsch/
实现参考:http://blog.csdn.net/allen_zhao_2012/article/details/7941631