繁体   English   中英

使用 JAVA API 在远程服务器上执行 shell 脚本

[英]Using JAVA API to execute shell script on remote server

我正在尝试使用 JAVA API 在远程服务器上运行 shell 脚本。 远程服务器有身份验证,所以我必须传递我的用户名和密码才能登录。 我无权在这些机器(源或目标)上安装 'sshpass' ,以防您要提供该解决方案。

做到这一点的最佳方法是什么?

JSch 是一个优秀的库,用于支持通过 ssh 的远程连接,包括远程命令(或 shell 脚本)的执行。

JSch 示例中有许多关于如何使用 JSch 的示例,但要特别注意Exec

在它的基础上,人们所做的是:

  1. 获取凭据
  2. 创建Session
  3. Session打开一个Channel
  4. 根据需要处理流

在打字时,OP 还发布了一个附加问题和一个示例。 http://www.codesandscripts.com/2014/10/java-program-to-execute-shell-scripts-on-remote-server.html 中的示例似乎也不错。

至于将脚本推送到服务器,首先使用scpsftp (我们发现后者更可靠)将文件移动到远程机器,确保发送chmod u+xexec ,然后调用脚本。

这是一个 JSch 示例,用于通过 SSH 登录(密码)远程服务器并运行 shell 脚本。

package com.mkyong.io.howto;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class RunRemoteScript {

    private static final String REMOTE_HOST = "1.1.1.1";
    private static final String USERNAME = "";
    private static final String PASSWORD = "";
    private static final int REMOTE_PORT = 22;
    private static final int SESSION_TIMEOUT = 10000;
    private static final int CHANNEL_TIMEOUT = 5000;

    public static void main(String[] args) {

        String remoteShellScript = "/root/hello.sh";

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // not recommend, uses jsch.setKnownHosts
            //jschSession.setConfig("StrictHostKeyChecking", "no");

            // authenticate using password
            jschSession.setPassword(PASSWORD);

            // 10 seconds timeout session
            jschSession.connect(SESSION_TIMEOUT);

            ChannelExec channelExec = (ChannelExec) jschSession.openChannel("exec");

            // run a shell script
            channelExec.setCommand("sh " + remoteShellScript + " mkyong");

            // display errors to System.err
            channelExec.setErrStream(System.err);

            InputStream in = channelExec.getInputStream();

            // 5 seconds timeout channel
            channelExec.connect(CHANNEL_TIMEOUT);

            // read the result from remote server
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: "
                         + channelExec.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            channelExec.disconnect();

        } catch (JSchException | IOException e) {

            e.printStackTrace();

        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }

    }
}

参考这个例子How to run a remote shell script in Java

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM