【问题标题】:Using JAVA API to execute shell script on remote server使用 JAVA API 在远程服务器上执行 shell 脚本
【发布时间】:2016-07-24 07:58:45
【问题描述】:

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

最好的方法是什么?

【问题讨论】:

  • 您是否仅限于标准 JDK?
  • 是的,我正在使用 jdk 8。
  • 根据您对 sshpass 的评论,这是通过 ssh 实现的吗?恕我直言,在远程机器上调用脚本的最佳方式是使用JSch。我们一直在工作中使用 JSch。如果从头开始编写,则需要考虑很多事情。那么,再次,您是否仅限于标准 JDK 中的类,还是可以使用外部库?
  • 哦,是的,我可以使用外部库。你能分享一些示例代码吗?
  • 这个例子就足够了。查了一下jsch

标签: java shell api ssh


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    JSch Examples 有很多关于如何使用 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(我们发现后者更可靠)将文件移动到远程机器,一定要发送一个execchmod u+x,然后调用脚本。

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2017-09-26
      • 2012-10-20
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多