2017-02-24
在自动化测试的时候,需要远程操控服务器做一些操作,比如切日、起服务器、执行某些脚本。如何实现?
我们可以利用JSch,远程执行脚本。JSch是Java Secure Channel的缩写,是一个SSH2功能的纯Java实现,具体信息可以参考JSch官网。它允许你连接到一个SSH服务器,并且可以使用端口转发,X11转发,文件传输等,同时你也可以集成它的功能到你自己的应用程序。在使用前,需要下载并导入JSch包:jsch-0.1.50.jar。
以下是实现代码通过JSch远程Windows系统和Linux系统执行脚本。其中Windows系统需要安装freeSSHd,具体步骤可查看终端模拟工具:Xshell 4。
1 pom.xml
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.53</version> </dependency>
2 SshUtil.java
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; public class SshUtil { public static String exec(String host, String user, String psw, int port, String command) { String result = ""; Session session = null; ChannelExec openChannel = null; try { JSch jsch = new JSch(); // getSession()只是创建一个session,需要设置必要的认证信息之后,调用connect()才能建立连接。 session = jsch.getSession(user, host, port); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.setPassword(psw); session.connect(); // 调用openChannel(String type) // 可以在session上打开指定类型的channel。该channel只是被初始化,使用前需要先调用connect()进行连接。 // Channel的类型可以为如下类型: // shell - ChannelShell // exec - ChannelExec // direct-tcpip - ChannelDirectTCPIP // sftp - ChannelSftp // subsystem - ChannelSubsystem // 其中,ChannelShell和ChannelExec比较类似,都可以作为执行Shell脚本的Channel类型。它们有一个比较重要的区别:ChannelShell可以看作是执行一个交互式的Shell,而ChannelExec是执行一个Shell脚本。 openChannel = (ChannelExec) session.openChannel("exec"); openChannel.setCommand(command); int exitStatus = openChannel.getExitStatus(); System.out.println(exitStatus); openChannel.connect(); InputStream in = openChannel.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); String buf = null; while ((buf = reader.readLine()) != null) { result += " " + buf; } } catch (JSchException e) { result += e.getMessage(); } catch (IOException e) { result += e.getMessage(); } finally { if (openChannel != null && !openChannel.isClosed()) { openChannel.disconnect(); } if (session != null && session.isConnected()) { session.disconnect(); } } return result; } }