sshj:如何将输入通过管道传输到自动化的主机端脚本

sshj: How to pipe input to automated host-side script

那么,情况是这样的:

我想使用 sshj 库连接到主机,该主机在连接时自动 运行s 脚本。假设脚本只记录它收到的任何 json 格式的输入。在终端中,我可以 运行 类似的东西:

echo '{ "name" : "Hubert", "status" : "alive" }' | ssh -i ~/.ssh/id_ed25519 user@host.com

连接后主机会记录信息 { "name" : "Hubert", "status" : "alive" }。

上述命令在 sshj 中的(等效)实现是什么样的?

好吧,我不是 100% 确定我在下面的代码中所做的一切是否是完全必要的,但它对我有用:

final SSHClient ssh = new SSHClient();
/* 
 * Connect to host and authenticate
 */
try (Session session = ssh.startSession()){
        // open a shell on host
        final Shell shl = session.startShell();
        
        // just a thread to stream stdout of host
        Thread t = new Thread() {
                @Override
                public void run() {
                        try {
                                InputStream in = shl.getInputStream();
                                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                                String line;
                                while ((line = br.readLine()) != null) {
                                        System.out.println("## " + line);
                                }
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        };
        t.start();

        // another thread to stream stderr of host
        Thread err_t = new Thread() {
                @Override
                public void run() {
                        try {
                                InputStream in = shl.getErrorStream();
                                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                                String line;
                                while ((line = br.readLine()) != null) {
                                        System.out.println("## " + line);
                                }
                        } catch (Exception e) {
                                e.printStackTrace();
                        }
                }
        };
        err_t.start();
        
        // you might want to escape the input string
        String input = "Some String";
        byte[] data = input.getBytes();
        // getOutputStream() corresponds to the hosts stdin
        OutputStream out = shl.getOutputStream();
        out.write(data);
        // ensure all written bytes get flushed to host
        out.flush();
        out.close();
        shl.join(5, TimeUnit.SECONDS);
        shl.close();
    } finally {
        ssh.disconnect();
    }