如何使用 Java 在远程系统上运行 SSH 命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2514439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:42:01  来源:igfitidea点击:

How do I run SSH commands on remote system using Java?

javacommand-linesshjsch

提问by sweety

I am new to this kind of Java application and looking for some sample code on how to connect to a remote server using SSH , execute commands, and get output back using Java as programming language.

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

回答by bobah

Have a look at Runtime.exec() Javadoc

看看 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();

回答by KarlP

I used ganymede for this a few yeas ago... http://www.cleondris.ch/opensource/ssh2/

几年前我为此使用过木卫二... http://www.cleondris.ch/opensource/ssh2/

回答by mehdi ali soltani

JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.

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

You can use exec.java.

您可以使用exec.java.

回答by neyc

You may take a look at this Java based framework for remote command execution, incl. via SSH: https://github.com/jkovacic/remote-execIt relies on two opensource SSH libraries, either JSch (for this implementation even an ECDSA authentication is supported) or Ganymed (one of these two libraries will be enough). At the first glance it might look a bit complex, you'll have to prepare plenty of SSH related classes (providing server and your user details, specifying encryption details, provide OpenSSH compatible private keys, etc., but the SSH itself is quite complex too). On the other hand, the modular design allows for simple inclusion of more SSH libraries, easy implementation of other command's output processing or even interactive classes etc.

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

回答by Pavan Kumar

Below is the easiest way to SSh in java. Download any of the file in the below link and extract, then add the jar file from the extracted file and add to your build path of the project http://www.ganymed.ethz.ch/ssh2/and use the below method

下面是在 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);

        }
    }

回答by Leonid Dashko

I created solution based on JSchlibrary:

我创建了基于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()
    }
}