【问题标题】:How do I run SSH commands on remote system using Java? [closed]如何使用 Java 在远程系统上运行 SSH 命令? [关闭]
【发布时间】:2011-01-31 15:34:07
【问题描述】:

我是这种 Java 应用程序的新手,正在寻找一些关于如何使用 SSH 连接到远程服务器、执行命令以及使用 Java 作为编程语言获取输出的示例代码。

【问题讨论】:

标签: java command-line ssh jsch


【解决方案1】:

看看 Runtime.exec() Javadoc

Process p = Runtime.getRuntime().exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

out.println("ls -l /home/me");
while (in.ready()) {
  String s = in.readLine();
  System.out.println(s);
}
out.println("exit");

p.waitFor();

【讨论】:

  • @Zubair - 给出 -1 的人懒得解释他的观点。该解决方案确实有效,因为它尽可能简单。虽然它不是“纯 Java”,这是一个缺点,但如果你在 Linux 上,不使用第三方库就无法让它变得更简单。
  • 你将如何处理密码?
  • @mors - #1 密钥认证,#2 - 与子进程的任何其他输入/输出相同
  • 这不起作用,至少您可以测试您的代码并发现没有Runtime.exec,而是Runtime.getInstance.exec。即使进行了这种更正,ls 的输出也没有显示。
  • @David - 在 Linux 上从命令行尝试Runtime.getRuntime().exec()
【解决方案2】:

几年前我用过ganymede...http://www.cleondris.ch/opensource/ssh2/

【讨论】:

    【解决方案3】:

    JSch 是 SSH2 的纯 Java 实现,可帮助您在远程机器上运行命令。 你可以找到它here,还有一些例子here

    您可以使用exec.java

    【讨论】:

      【解决方案4】:

      您可以查看这个基于 Java 的远程命令执行框架,包括。通过 SSH:https://github.com/jkovacic/remote-exec 它依赖于两个开源 SSH 库,要么是 JSch(对于这个实现,甚至支持 ECDSA 身份验证),要么是 Ganymed(这两个库中的一个就足够了)。乍一看可能有点复杂,你必须准备很多 SSH 相关的类(提供服务器和你的用户详细信息,指定加密详细信息,提供 OpenSSH 兼容的私钥等,但 SSH 本身相当复杂也)。另一方面,模块化设计允许简单地包含更多 SSH 库,轻松实现其他命令的输出处理甚至交互类等。

      【讨论】:

        【解决方案5】:

        以下是在 java 中进行 SSH 的最简单方法。下载以下链接中的任何文件并提取,然后从提取的文件中添加 jar 文件并添加到项目的构建路径中 http://www.ganymed.ethz.ch/ssh2/ 并使用以下方法

        public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
                System.out.println("inside the ssh function");
                try
                {
                    Connection conn = new Connection(serverIp);
                    conn.connect();
                    boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
                    if (isAuthenticated == false)
                        throw new IOException("Authentication failed.");        
                    ch.ethz.ssh2.Session sess = conn.openSession();
                    sess.execCommand(command);  
                    InputStream stdout = new StreamGobbler(sess.getStdout());
                    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                    System.out.println("the output of the command is");
                    while (true)
                    {
                        String line = br.readLine();
                        if (line == null)
                            break;
                        System.out.println(line);
                    }
                    System.out.println("ExitCode: " + sess.getExitStatus());
                    sess.close();
                    conn.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace(System.err);
        
                }
            }
        

        【讨论】:

        • 这个可以在spring boot中完成吗?
        【解决方案6】:

        我基于JSch库创建了解决方案:

        import com.google.common.io.CharStreams
        import com.jcraft.jsch.ChannelExec
        import com.jcraft.jsch.JSch
        import com.jcraft.jsch.JSchException
        import com.jcraft.jsch.Session
        
        import static java.util.Arrays.asList
        
        class RunCommandViaSsh {
        
            private static final String SSH_HOST = "test.domain.com"
            private static final String SSH_LOGIN = "username"
            private static final String SSH_PASSWORD = "password"
        
            public static void main() {
                System.out.println(runCommand("pwd"))
                System.out.println(runCommand("ls -la"));
            }
        
            private static List<String> runCommand(String command) {
                Session session = setupSshSession();
                session.connect();
        
                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                try {
                    channel.setCommand(command);
                    channel.setInputStream(null);
                    InputStream output = channel.getInputStream();
                    channel.connect();
        
                    String result = CharStreams.toString(new InputStreamReader(output));
                    return asList(result.split("\n"));
        
                } catch (JSchException | IOException e) {
                    closeConnection(channel, session)
                    throw new RuntimeException(e)
        
                } finally {
                    closeConnection(channel, session)
                }
            }
        
            private static Session setupSshSession() {
                Session session = new JSch().getSession(SSH_LOGIN, SSH_HOST, 22);
                session.setPassword(SSH_PASSWORD);
                session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
                session.setConfig("StrictHostKeyChecking", "no"); // disable check for RSA key
                return session;
            }
        
            private static void closeConnection(ChannelExec channel, Session session) {
                try {
                    channel.disconnect()
                } catch (Exception ignored) {
                }
                session.disconnect()
            }
        }
        

        【讨论】:

        • 这对我来说就像一个魅力谢谢!
        猜你喜欢
        • 2013-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-04
        • 2018-03-03
        • 2015-12-23
        • 2015-01-24
        • 2013-02-01
        相关资源
        最近更新 更多