Java 中 链接 Linux 的静态类

Java 中 链接 Linux 的静态类

此文件会随着时间不断更新

所需要的包

<ganymed-ssh2.version>262</ganymed-ssh2.version>
<!-- 链接 Liunx 软件 -->
<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh2</artifactId>
	<version>${ganymed-ssh2.version}</version>
</dependency>

**静态类如下: **
有代码可知返回值是以 Linux 控制台输出的内容且一行为一个 add(), 最后形成 List;

package com.YKenan.YKenan.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Linux {

    /**
     * 链接 Liunx 的参数
     * ip: ip地址
     * port: 端口号
     * username: 用户名
     * pwd: 密码
     */
    private String ip = "10.100.10.100";
    private int port = 22;
    private String userName = "root";
    private String pwd = "YKenanYKenan";

    private Connection connection = new Connection(ip, port);

    public List<String> getExecCommand(String string) throws IOException {
        List<String> result = new ArrayList<>();
        connection.connect();// 连接
        boolean authenticateWithPassword = connection.authenticateWithPassword(userName, pwd);// 认证
        if (!authenticateWithPassword || !login()) {
            throw new IOException("Authentication failed.");
        } else {
            Session session = connection.openSession();
            session.execCommand(string, "utf-8");
            StreamGobbler stdout = new StreamGobbler(session.getStdout());
            StreamGobbler stderr = new StreamGobbler(session.getStderr());
            BufferedReader stdoutBuffere = new BufferedReader(new InputStreamReader(stdout));
            BufferedReader stderrstdoutBuffere = new BufferedReader(new InputStreamReader(stderr));
            for (String line = stdoutBuffere.readLine(); line != null; line = stdoutBuffere.readLine()) {
                result.add(line + "\n");
            }
            for (String line = stderrstdoutBuffere.readLine(); line != null; line = stderrstdoutBuffere.readLine()) {
                result.add(line);
            }
            stdoutBuffere.close();
            stderrstdoutBuffere.close();
            session.close();
        }
        connection.close();
        return result;
    }

    private Boolean login() {
        boolean flg = false;
        try {
            connection = new Connection(ip);
            connection.connect();// 连接 //判断身份是否已经认证
            if (!connection.isAuthenticationComplete()) {
                // 加锁,防止多线程调用时线程间判断不一致,导致出现重复认证
                synchronized (this) {
                    if (!connection.isAuthenticationComplete()) { // 进行身份认证
                        flg = connection.authenticateWithPassword(userName, pwd);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flg;
    }

}

你可能感兴趣的:(java,Liunx,静态类,Java,SpringMVC,开发)