Execute Linux command framework under Java-sshxcute

Source: Internet
Author: User
Sshxcute Guideline 1. Overview

As its name indicates, the Sshxcute is a framework. It is designed to let engineers to the use Java call to execute command/script on remote Linux/unix system through SSH Connec tion Way, which make software testing or system deployment easier and specifically to make it easier to automate software Testing and system environment deployment.

Sshxcute is designed with the following points at Mind:minimum machine use SSH requirements–only 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 is easy to create the other task Typ E to plug into Sshxcute.

2. limitation and scope 2.1 limitation Remote system should o Pen SSH connection with credential enabled. 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, are to is run on remote system maybe deploying development or production SYS TEM environment), and you are developing a script to invoke every command/script is too complex. And your 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 your have requirements to run some configuration commands/scripts on Remot E Linux/unix system, Sshxcute is just the ideal tool to help you achieve your goal! Just Import the jar and your can invoke Sshxcute API in your project. 3. How to use

The must import Sshxcute.jar into the your $CLASSPATH, so and can use it. The section below indicates the builds 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 three steps can be stimulated and finished by Sshxcute Java API.

Initialize a Connbean object, parameter list is IP, username, password Connbean
cb = new Connbean ("IP", "username" , "password");
Put the Connbean instance as parameter for sshexec static method getinstance (Connbean) to retrieve a singleton sshexec          instance
SSH = sshexec.getinstance (CB);
//Connect to Server
ssh.connect ();

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

The 5th step are 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'll explain that. Because it is so obvious this if you have OO programming experience, and you'll fell it is very 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 the shows the class diagram for ExecCommand, Execshellscript and CustomTask.

The only parameter to 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 in Sshexec.exec (CustomTask) method and then it begins to run. 3.3 Execute shell script on remote system

It is almost the same way as 3.2 Execute command in remote system section. For example, if we want to execute sshxcute_test.sh on remote system at/home/tsadmin with two ' 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 execshells Cript (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 in our local machine and we want to execute it on remote system, of Course, we should the script to remote system upload. That can is done by Sshxcute Java API as. For example, we want to upload all files under C:/data2/data on the 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 the local machine to/home/tsadmin on remote system, we can

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

Note so 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 connection ssh.uploadsingledatatoserver ("data/sshxcute_test.sh", "/home/tsadmin"); Ssh.exec (CT1);  //before execution 

uploading does not limit to help executing shell scripts, can use uploading function based on the simple Requirem Ent–just upload files to remote sytem. 3.5 result handle

All task including execcommand and execshellscript or even what we are discuss the about later task when customized G them, a result handle can is returned. The handle is a result object with return code, System printout, and error message printout. What ' s more, your can get a Boolean variable–issuccess to indicate whether tasks run successfully or not.

In the section 4.1, we'll have a task ' s status (OK or fail), which is configurable too. Sshxcute determine.

For example, your can get a result object this returned from a sshexec.exec (CustomTask) method. And can use the 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 this job.

Initialize a sshexec instance without referring any object.
Sshexec ssh = null; Wrap the whole execution jobs into Try-catch blocks   try {   //Initialize a Connbean object, Paramet
Er 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 Custom
Task     CustomTask ct1 = new ExecCommand ("chmod 755/home/tsadmin/sshxcute_test.sh");    //Create a execshellscript, the reference class must be CustomTask     CustomTask ct2 = new execs
Hellscript ("/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:"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.