Javaの練習 - リモートシェルスクリプトを呼び出し、出力情報を取得します

図1に示すように、依存関係を追加

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

  1. まず、ログインIPアドレスのニーズを渡して、コネクタを構築します。
Connection conn = new Connection(ipAddr);
  1. ユーザー名とパスワードを渡しシミュレー着陸先サーバ、;
boolean isAuthenticated = conn.authenticateWithPassword(userName, passWord);

これは、ブール値を返し、真の代表は、正常先サーバーに上陸した、または着陸に失敗しました。

  1. Linuxのスクリプトが必要なコマンドを実行すると、セッションを開きます。
Session session = conn.openSession();
session.execCommand(“ifconfig”);
  1. コンソールは、ターゲットサーバを受信するBRの内容を読み取り、結果を返します。
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
  1. 0成功した非0-失敗:スクリプト実行中の成功のシンボルを取得
System.out.println(“ExitCode: ” + session.getExitStatus());
  1. クローズドセッションおよび接続
session.close();
conn.close();

ヒント:

  1. カレントディレクトリの第二部によって成功した認証が/ home /ユーザー名/ディレクトリの下に配置された後、あなたが配置されているスクリプトファイルの絶対パスを指定することができ、またはスクリプトファイルは、その後、必要なスクリプトの実行パラメータを渡す場所をCDでディレクトリに移動し、完全なスクリプトが呼び出されます。
  2. スクリプトの実行後、スクリプトはテキストの実装の結果を得ることができ、これらは文字化けを避けるために、適切に戻ってクライアントにテキストをエンコードする必要があります。
  3. あなたは、このような最初のスクリプトなど、複数のLinuxスクリプトコンソールを実行する必要がある場合、結果は上院に2番目のスクリプトで返し、複数のセッションを開く必要があり、それは、複数の呼び出しで
    、セッションのSES = conn.openSession();、使用後は、それを閉じることを忘れないでください。

例3:ツール

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、テストスクリプト

echo "Hello"

出力
出力

おすすめ

転載: www.cnblogs.com/Jacian/p/11493351.html