Java下執行linux 命令架構-sshxcute

來源:互聯網
上載者:User
sshxcute Guideline 1. Overview

As its name indicates, SSHXCUTE is a framework. It was designed to let engineers to use Java call to execute command/script on remote Linux/UNIX system through SSH connection way, which make software testing or system deployment easier and specifically to make it easier to automate software testing and system environment deployment.

SSHXCUTE was designed with the following points in mind: Minimum machine requirements – Only use SSH protocol to connect. Easily useable - Engineers use Java code to execute command/script. Build-in executing command/script task type Easily extendable - This means that it should be easy to create other task type to plug into sshxcute.

2. Limitation and scope 2.1 Limitation Remote system should open SSH connection with credential enabled. You can only plug sshxcute into Java based project. JDK version newer or equal to 5.0 2.2 Scope

Scenario 1. If you have a batch of commands/scripts that are to be run on remote system (maybe deploying development or production system environment), and you think developing a script to invoke every command/script is too complex. And you have one Java IDE (like Eclipse) on your windows/Linux, why not try to execute through your client side?

Scenario 2. Your automation tool is implemented by Java, and you have requirements to run some configuration commands/scripts on remote Linux/UNIX system, sshxcute is just the ideal tool to help you achieve your goal! Just import the jar and you can invoke sshxcute API in your project. 3. How to use

First, you must import sshxcute.jar into your $CLASSPATH, so that you can use it. The section below indicates the build path settings for a Java project in Eclipse IDE. You can reach this through the project properties (Project > Properties > Java Build Path). More detail please search online.

3.1 Preparation

Usually when we want to run commands or scripts on remote Linux/UNIX system, the common steps are: 1) Open SSH client tool (e.g. Putty console). 2) Enter ip address. 3) Enter username and password to login. 4) When prompted login successful, enter command to execute. 5) Log out.

The first three steps can be stimulated and finished by sshxcute Java API.

// Initialize a ConnBean object, parameter list is ip, username, passwordConnBean cb = new ConnBean("ip ", "username","password");// Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instancessh = SSHExec.getInstance(cb);          // Connect to serverssh.connect();

The 4th step is the core jobs that we want to do – executing commands/scripts. Please see below section for more information.

The 5th step is used to disconnect from server:

ssh.disconnect();
3.2 Execute command on remote system

Let’s jump into sshxcute Java API code directly, then later we will explain that. Because it is so obvious that if you have OO programming experience, you will fell it is so easy.

CustomTask sampleTask = new ExecCommand("echo 123");ssh.exec(sampleTask);

ExecCommand class extends CustomTask class, we create ExecCommand object that has a CustomTask class type reference. Below picture shows the class diagram for ExecCommand, ExecShellScript and CustomTask.

The only parameter for ExecCommand constructor is the command string. Note to execute multiple commands, you can separate them by delimiter “,”. For example:

CustomTask sampleTask = new ExecCommand("echo 123", "echo 456,"echo 789");

ExecCommand constructor is public ExecCommand(String...args)

Put the ExecCommand instance as argument into SSHExec.exec(CustomTask) method, then it begins to run. 3.3 Execute shell script on remote system

It is almost the same way as 3.2 Execute command on remote system section. For example, if we want to execute sshxcute_test.sh on remote system at /home/tsadmin with two arguments “hello world”, we should invoke sshxcute Java API like below:

CustomTask ct1 = new ExecShellScript("/home/tsadmin","./sshxcute_test.sh","hello world");ssh.exec(ct1);

ExecShellScript constructor is public ExecShellScript(String workingDir, String shellPath, String args) public ExecShellScript(String shellPath, String args) public ExecShellScript(String shellPath)

3.4 Upload files to remote system

Here comes one problem, what if the shell script saved at our local machine and we want to execute it on remote system, of course, we should first upload that script to remote system. That can be done by sshxcute Java API as well. For example, we want to upload all files under c:/data2/data on local machine to /home/tsadmin on remote system, we can

ssh.uploadAllDataToServer("c:/data2/data", "/home/tsadmin");

Or if we want to upload single file on local machine to /home/tsadmin on remote system, we can

ssh.uploadSingleDataToServer("data/sshxcute_test.sh","/home/tsadmin");

Note that we should put upload work before execution and after connection. For example,

CustomTask ct1 = new ExecShellScript("/home/tsadmin","./sshxcute_test.sh","hello world");ssh.connect();  // After connectionssh.uploadSingleDataToServer("data/sshxcute_test.sh", "/home/tsadmin");ssh.exec(ct1);  // Before execution

Uploading does not limit to help executing shell scripts, you can use uploading function based on the simple requirement – just upload files to remote sytem. 3.5 Result handle

All task including ExecCommand and ExecShellScript or even what we will discuss later about customized task, when executing them, a result handle can be returned. The handle is a Result object with return code, system printout, error message printout. What’s more, you can get a Boolean variable – isSuccess to indicate whether tasks run successfully or not.

In section 4.1, we will see more on how SSHXCUTE determine a task’s status (OK or fail), that is configurable too.

For example, you can get a Result object that returned from a SSHExec.exec(CustomTask) method. And you can use logical algorithm to print out message information.

Result res = ssh.exec(task);if (res.isSuccess){    System.out.println("Return code: " + res.rc);    System.out.println("sysout: " + res.sysout);}else{    System.out.println("Return code: " + res.rc);    System.out.println("error message: " + res.error_msg);}
3.6 Whole story

Assume we want to run a shell script a Linux server (e.g. ip is 9.125.71.115). About sshxcute_test.sh, please refer to Appendix A.

Below is the Java code to finish that job.

// Initialize a SSHExec instance without referring any object. SSHExec ssh = null;// Wrap the whole execution jobs into try-catch block   try {    // Initialize a ConnBean object, parameter list is ip, username, password    ConnBean cb = new ConnBean("9.125.71.115", "username","password");    // Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a real SSHExec instance    ssh = SSHExec.getInstance(cb);                  // Create a ExecCommand, the reference class must be CustomTask    CustomTask ct1 = new ExecCommand("chmod 755 /home/tsadmin/sshxcute_test.sh");    // Create a ExecShellScript, the reference class must be CustomTask    CustomTask ct2 = new ExecShellScript("/home/tsadmin","./sshxcute_test.sh","hello world");    // Connect to server    ssh.connect();    // Upload sshxcute_test.sh to /home/tsadmin on remote system    ssh.uploadSingleDataToServer("data/sshxcute_test.sh", "/home/tsadmin");    // Execute task    ssh.exec(ct1);    // Execute task and get the returned Result object    Result res = ssh.exec(ct2);    // Check result and print out messages.    if (res.isSuccess)    {        System.out.println("Return code: " 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.