SoFunction
Updated on 2025-04-13

Java operation SSH2 to implement remote execution of linux commands

Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>

SSH2Util tool class encapsulation

import .;
import .;

import ;
import ;
import ;
import ;

public class SSH2Util {

    //Specify the default encoding    private static String DEFAULT_CHARSET = "UTF-8";

    /**
      * EstablishSSH2connect
      * @param host Host address
      * @param username username
      * @param password password
      * @return Connection
      */
    public static Connection openConnection(String host,String username,String password) {
        try {
            Connection connection = new Connection(host);
            //Create ssh2 connection            ();
            //Check the username            boolean login = (username,password);
            if (login){
                (host + "Connected successfully");
                return connection;
            }else {
                throw new RuntimeException(host + "Username and password are incorrect");
            }
        } catch (Exception e) {
            throw new RuntimeException(host +" "+ e);
        }
    }

    /**
      * Execute the command
      * @param connection ssh2 connection object
      * @param command command statement
      * @return Execution result, encapsulate execution status and execution result
      */
    public static ExecCmdResult execCommand(Connection connection,String command){
        ExecCmdResult execCmdResult = new ExecCmdResult();
        Session session = null;
        try{
            session = ();
            //Execute the command            (command);
            //Analysis results            String result = parseResult(());
            //The parsing result is empty, which means that an error occurred in the execution command. Trying to parse the error to output the output            if (result == null||()==0){
                result = parseResult(());

            }else {
                (true);
            }
            //Set response results            (result);
            (command + " ==&gt;&gt; " +());
            return execCmdResult;

        }catch (Exception e){
            ();
        }
        return null;
    }

    public static String parseResult(InputStream inputStream) throws IOException{
        //Read the output stream content        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,DEFAULT_CHARSET));
        StringBuffer resultSB = new StringBuffer();
        String line;
        while((line = ()) != null){
            (line+"\n");
        }
        //Replace newline characters        String result = ().replaceAll("[\\t\\n\\r]", "");
        return result;

    }
}

ExecCmdResult defines the return result class

public class ExecCmdResult {

    //Whether the command execution is successful    private boolean flag ;
    //Output result    private String result;

    public void setFlag(boolean success){
         = success;
    }

    public boolean getFlag() {
        return flag;
    }

    public String getResult(){
        return result;
    }
    public void setResult(String result){
         = result;
    }

}

SSH2Demo Test

import .;

public class SSH2Demo {

    public static void main(String[] args) {
        try {
            String host = "168.192.22.7";
            String username = "root";
            String password = "123456";
            Connection connection = (host,username,password);
            String cpuInfo = "cat /proc/cpuinfo | grep \"cpu cores\" | uniq"; // Server number            ExecCmdResult cup = (connection,cpuInfo);
            ();
        }
        catch (Exception a){
            ();
        }
    }
}

This is the article about Java operation SSH2 to implement remote execution of linux commands. For more related content on Java SSH2 to execute linux commands, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!