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

swe*_*ety 27 java ssh command-line jsch

我是这类Java应用程序的新手,正在寻找一些示例代码,介绍如何使用SSH连接到远程服务器,执行命令,并使用Java作为编程语言获取输出.

bob*_*bah 16

看看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();
Run Code Online (Sandbox Code Playgroud)

  • @Zubair - 给出 -1 的那个人并没有费心解释他的观点。此解决方案确实有效,因为它尽可能简单。虽然它不是“纯 Java”,但这是一个缺点,但如果您使用的是 Linux,则不使用第三方库就无法使其更简单。 (2认同)

小智 12

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

你可以用exec.java.


小智 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);

        }
    }
Run Code Online (Sandbox Code Playgroud)


Leo*_*hko 5

我创建了基于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()
    }
}
Run Code Online (Sandbox Code Playgroud)