1. Add dependencies

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
Copy the code

2. Api description

  1. First, construct a connector and pass in an IP address that needs to be logged in.
Connection conn = new Connection(ipAddr);
Copy the code
  1. Simulate login destination server, pass in user name and password;
boolean isAuthenticated = conn.authenticateWithPassword(userName, passWord);
Copy the code

It returns a Boolean value, true for successful login to the destination server, otherwise failed.

  1. Open a session and execute the Linux script commands you need;
Session session = conn.openSession(); Session. ExecCommand (" ifconfig ");Copy the code
  1. Receives results from the console on the target server and reads the contents of the BR;
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
Copy the code
  1. The script is successfully executed or not: 0- success is not 0- failure
System. The out. Println (" ExitCode: "+ session. GetExitStatus ());Copy the code
  1. Disable session and Connection
session.close();
conn.close();
Copy the code

Tips:

  1. After passing the second authentication, the current directory is in the /home/username/ directory. You can specify the absolute path of the script file, or use CD to navigate to the directory where the script file is located, and then pass the parameters required for executing the script to complete the script invocation.
  2. After the script is executed, you can obtain the script execution result text. You need to encode the text correctly and return it to the client to avoid garbled characters.
  3. If you need to execute multiple Linux console scripts, such as the return of the first script as an entry to the second script, you must open multiple sessions, i.e. call Session sess = conn.openSession() multiple times; Remember to turn it off after use.

3. Example: Utility classes

public class SSHTool {

    private Connection conn;
    private String ipAddr;
    private Charset charset = StandardCharsets.UTF_8;
    private String userName;
    private String password;

    public SSHTool(String ipAddr, String userName, String password, Charset charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if(charset ! =null) {
            this.charset = charset; }}/** * Log in to the remote Linux host **@returnCheck whether the login is successful */
    private boolean login(a) {
        conn = new Connection(ipAddr);

        try {
            / / the connection
            conn.connect();
            / / certification
            return conn.authenticateWithPassword(userName, password);
        } catch (IOException e) {
            e.printStackTrace();
            return false; }}/** * Execute the Shell script or command **@paramCMDS command line sequence *@returnThe script output is */
    public StringBuilder exec(String cmds) throws IOException {
        InputStream in = null;
        StringBuilder result = new StringBuilder();
        try {
            if (this.login()) {
                // Open a session
                Session session = conn.openSession();
                session.execCommand(cmds);
                in = session.getStdout();
                result = this.processStdout(in, this.charset); conn.close(); }}finally {
            if (null != in) {
                in.close();
            }
        }
        return result;
    }

    /** * Parses the stream to get string information **@paramIn Input stream object *@paramCharset character set *@returnThe script output is */
    public StringBuilder processStdout(InputStream in, Charset charset) throws FileNotFoundException {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
// OutputStream os = new FileOutputStream("./data.txt");
        try {
            int length;
            while((length = in.read(buf)) ! = -1) {
// os.write(buf, 0, c);
                sb.append(new String(buf, 0, length)); }}catch (IOException e) {
            e.printStackTrace();
        }
        return sb;
    }

    public static void main(String[] args) throws IOException {
        SSHTool tool = new SSHTool("192.168.100.40"."root"."123456", StandardCharsets.UTF_8);
        StringBuilder exec = tool.exec("bash /root/test12345.sh"); System.out.println(exec); }}Copy the code

4. Test scripts

echo "Hello"
Copy the code

The output