JSch远程执行脚本
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
com.jcraft
jsch
0.1.53
2 SshUtil.java


packagetest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importcom.jcraft.jsch.ChannelExec;importcom.jcraft.jsch.JSch;importcom.jcraft.jsch.JSchException;importcom.jcraft.jsch.Session;public classSshUtil {public static String exec(String host, String user, String psw, intport, String command) {
String result= "";
Session session= null;
ChannelExec openChannel= null;try{
JSch jsch= newJSch();//getSession()只是创建一个session,需要设置必要的认证信息之后,调用connect()才能建立连接。
session =jsch.getSession(user, host, port);
java.util.Properties config= newjava.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= newBufferedReader(newInputStreamReader(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();
}
}returnresult;
}
}
View Code
3 Client.java


packagetest;public classClient {public static voidmain(String[] args) {
ExecuteCmdOnWin();
}private static voidExecCmdOnLinux() {
String ip= "xxx.xxx.xxx.xxx";int port = 22;
String user= "username";
String pwd= "password";
String batCommand= "ls";try{
System.out.println("系统执行的CMD命令是:\"[" + batCommand + "]\"");
System.out.println(SshUtil.exec(ip, user, pwd, port, batCommand));
Thread.sleep(1000);
Thread.sleep(1000);
}catch(Exception e) {
System.out.println("切日操作失败,请查找原因");
}
}private static voidExecuteCmdOnWin() {
String ip= "xxx.xxx.xxx.xxx";int port = 22;
String user= "username";
String pwd= "password";
String batCommand= "cmd /c \"start " + "C:/createFolder.bat" + "\"";//运行批处理,会打开一个cmd窗口,这里会执行命令kill cmd.exe 进程
String killCMD = "cmd /c \"taskkill /f /fi \"IMAGENAME eq cmd.exe\"\"";
String updatedatecommand= "cmd /c \"date " + "2017/2/24";
String dirCommand= "cmd /c dir";try{
System.out.println("系统执行的CMD命令是:\"[" + batCommand + "]\"");
System.out.println(SshUtil.exec(ip, user, pwd, port, batCommand));
System.out.println("系统执行的CMD命令是:\"[" + killCMD + "]\"");
System.out.println(SshUtil.exec(ip, user, pwd, port, killCMD));
System.out.println("系统执行的CMD命令是:\"[" + updatedatecommand + "]\"");
System.out.println(SshUtil.exec(ip, user, pwd, port,updatedatecommand));
System.out.println("系统执行的CMD命令是:\"[" + dirCommand + "]\"");
System.out.println(SshUtil.exec(ip, user, pwd, port, dirCommand));
}catch(Exception e) {
System.out.println("切日操作失败,请查找原因");
}
}
}
View Code
4 结果
4.1 Window


系统执行的CMD命令是:"[cmd /c "start C:/createFolder.bat"]"
-1
系统执行的CMD命令是:"[cmd /c "taskkill /f /fi "IMAGENAME eq cmd.exe""]"
-1
�ɹ�: ����ֹ PID Ϊ 3444 �Ľ��̡� �ɹ�: ����ֹ PID Ϊ 2860 �Ľ��̡� �ɹ�: ����ֹ PID Ϊ 2980 �Ľ��̡�
系统执行的CMD命令是:"[cmd /c "date 2017/2/24]"
-1
系统执行的CMD命令是:"[cmd /c dir]"
-1
������ C �еľ�û�б�ǩ�� ������к��� 3C69-84C5 C:\Users\Administrator\Desktop ��Ŀ¼ 2017/02/22 16:28
View Code
4.2 Linux


系统执行的CMD命令是:"[ls]"
-1
tmpfolder 公共的 模板 视频 图片 文档 下载 音乐 桌面
View Code
5 参考











