Search This Blog

Saturday, December 03, 2016

How to run a linux command from java code

How to run a linux command from java code
Download opensource java ssh client from 

Use the following java docs , to review the API



package client;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.sshtools.net.SocketTransport;
import com.sshtools.ssh.PasswordAuthentication;
import com.sshtools.ssh.SshAuthentication;
import com.sshtools.ssh.SshClient;
import com.sshtools.ssh.SshConnector;

import com.sshtools.ssh.SshSession;


public class Class1 {
    public Class1() {
        super();
    }

    public static void main(String[] args) throws Exception {
        Class1 class1 = new Class1();


        SshConnector con = SshConnector.createInstance();
         SshClient ssh = con.connect(new SocketTransport("localhost", 22),
                        "root");

         PasswordAuthentication pwd = new PasswordAuthentication();
         pwd.setPassword("Welcome1");

         if (ssh.authenticate(pwd) == SshAuthentication.COMPLETE) {
                System.out.println("Authentication succeeded");
                SshSession sesison = ssh.openSessionChannel();
         } else {
                System.out.println("Authentication failed");
         }

        if (ssh.isAuthenticated()) {

                SshSession session = ssh.openSessionChannel();
               session.executeCommand("xm list");
            

               InputStream stdout =  session.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                       System.out.println("the output of the command is");
                       while (true)
                       {
                           String line = br.readLine();
                           if (line == null)
                               break;
                           System.out.println(line);
                       }


                session.close();
                ssh.disconnect();


        }


    }
}



Tags: Publish
December 03, 2016 at 12:38PM
Open in Evernote