Java practice - Remote Shell calls the script and get the output information

1, adding a dependency

<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>

2, Api description

  1. First, construct a connector, passing a login ip address needs;
Connection conn = new Connection(ipAddr);
  1. Simulated landing destination server, passing a user name and password;
boolean isAuthenticated = conn.authenticateWithPassword(userName, passWord);

It returns a Boolean value, true representatives successfully landed on the destination server, or failed on landing.

  1. Open a session, execute linux script commands you need;
Session session = conn.openSession();
session.execCommand(“ifconfig”);
  1. Console receiving the target server returns the results, read the contents of br;
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
  1. Get script running success symbol: 0 successful Non-0- failure
System.out.println(“ExitCode: ” + session.getExitStatus());
  1. Closed session and connection
session.close();
conn.close();

Tips:

  1. After successful authentication by the second part of the current directory is located under / home / username / directory, you can specify an absolute path of the script file is located, or by cd navigate to the directory where the script file, then pass the script execution parameters required, complete script called.
  2. After the execution of the script, the script can get the results of the implementation of the text, these need to be properly encoded text back to the client, to avoid garbled.
  3. If you need to perform multiple linux script consoles, such as the first script returns the result is the second script to the Senate, you have to open multiple Session, that is, multiple calls
    Session sess = conn.openSession () ;, After use remember to close it.

Example 3: Tools

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;
        }
    }

    /**
     * 登录远程Linux主机
     *
     * @return 是否登录成功
     */
    private boolean login() {
        conn = new Connection(ipAddr);

        try {
            // 连接
            conn.connect();
            // 认证
            return conn.authenticateWithPassword(userName, password);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 执行Shell脚本或命令
     *
     * @param cmds 命令行序列
     * @return 脚本输出结果
     */
    public StringBuilder exec(String cmds) throws IOException {
        InputStream in = null;
        StringBuilder result = new StringBuilder();
        try {
            if (this.login()) {
                // 打开一个会话
                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;
    }

    /**
     * 解析流获取字符串信息
     *
     * @param in      输入流对象
     * @param charset 字符集
     * @return 脚本输出结果
     */
    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);
    }
}

4, test scripts

echo "Hello"

Output
Output

Guess you like

Origin www.cnblogs.com/Jacian/p/11493351.html