JSch遠程執行腳本


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

<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;
    }
}
View Code

3 Client.java

package test;

public class Client {
    public static void main(String[] args) {
        ExecuteCmdOnWin();
    }

    private static void ExecCmdOnLinux() {
        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 void ExecuteCmdOnWin() {
        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    <DIR>          . 2017/02/22  16:28    <DIR>          .. 2017/02/14  10:32             1,911 360��ȫ�����7.lnk 2016/09/22  17:46             1,047 Excel 2007.lnk 2017/02/22  16:28               948 FreeSSHd.lnk 2016/09/22  17:46             1,066 PowerPoint 2007.lnk 2016/09/22  17:46             1,059 Word 2007.lnk 2016/09/22  20:42             2,064 �����.lnk 2017/02/14  10:33             2,255 ������PPS.lnk 2017/01/24  10:16               993 װ���ر�.lnk 2017/02/14  10:32             1,913 �ṷ����.lnk                9 ���ļ�         13,256 �ֽ�                2 ��Ŀ¼ 76,647,092,224 �����ֽ�
View Code

4.2 Linux

系統執行的CMD命令是:"[ls]"
-1
 tmpfolder 公共的 模板 視頻 圖片 文檔 下載 音樂 桌面
View Code


5 參考

[1] Java實踐 — SSH遠程執行Shell腳本

[2] JSch基本使用

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM