java - 通过 ssh 发送命令并读取输出结果

标签 java ssh j2ssh

我有代码通过 ssh 连接到远程服务器并向其发送 2 个或更多命令(例如:cd/export/home/ops/bin 和 "./viewlinkload –time 20131205 -19"),但我没有看到执行的命令,也没有收到结果。

我需要获取服务器返回的结果并显示它。

这是代码发送命令:

try {
    command = "cd /export/home/ops/bin";
    command1="./viewlinkload –time 20131205-19";

    session.startShell();
session.getOutputStream().write(command.getBytes());
        ChannelInputStream in = session.getInputStream();
        ChannelOutputStream out = session.getOutputStream();
        InputStream inputStream = session.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
            stringBuilder.append('\n');
        }
        System.out.println("ke qua" + stringBuilder.toString());
        // return stringBuilder.toString();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

如果我更改命令是“ls\n”,则最后一条记录在“while ((line = bufferedReader.readLine()) != null)”处挂起并且不运行。 帮我。 谢谢大家。

最佳答案

Jsch 在示例目录中提供了一些优秀的示例,您可能会特别感兴趣的是 Exec。您可能还对 Shell

感兴趣

这是一个稍作修改的版本,它跳过从命令行获取信息并提示输入用户信息和命令,而只是尝试直接连接到远程计算机并执行 ls 命令。

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.InputStream;
import java.util.Properties;

public class TestShell {

    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            Session session = jsch.getSession("username", "computer", 22);

            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            // Skip prompting for the password info and go direct...
            session.setPassword("happybunnyslippers");
            session.connect();

            String command = "ls";

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();

            System.out.println("Connect to session...");
            channel.connect();

            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 (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

我在我的 Windows 机器上测试了这一点,连接到我的一台 Mac 机器,没有任何问题

更新了被黑的 Shell 示例

基本上,这是一个基于 Shell 示例的黑客示例。

这使用自定义OutputStream来监视从远程计算机发送的内容的更改,并且可以发出命令。这是非常基本的,事实上我所做的就是等待 $ 发送到输出流,然后发出下一个命令。

修改它不需要太多的工作,这样,基于当前的命令/命令索引,您就可以进行不同的解析...

import com.jcraft.jsch.*;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import javax.swing.*;

public class TestShell {

    public static void main(String[] arg) {

        try {

            JSch jsch = new JSch();
            String host = null;

            final Session session = jsch.getSession("user", "remotecomputer", 22);
            session.setPassword("fluffybunnyslippers");

            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(30000);   // making a connection with timeout.

            final Channel channel = session.openChannel("shell");

            PipedInputStream pis = new PipedInputStream();
            final PipedOutputStream pos = new PipedOutputStream(pis);

            channel.setInputStream(pis);
            channel.setOutputStream(new OutputStream() {

                private int cmdIndx = 0;
                private String[] cmds = {
                    "ls\n",
                    "cd ..\n",
                    "ls\n",
                    "exit\n"
                };

                private String line = "";

                @Override
                public void write(int b) throws IOException {
                    char c = (char) b;
                    if (c == '\n') {
                        logout(line);
                        System.out.print(line);
                        line = "";
                    } else {
                        line += c;
                        logout(line);
                        if (line.endsWith("$ ")) {
                            String cmd = cmds[cmdIndx];
                            cmdIndx++;
                            pos.write(cmd.getBytes());
                        }
                    }
                }

                public void logout(String line) {
                    if (line.startsWith("logout")) {
                        System.out.println("...logout...");
                        channel.disconnect();
                        session.disconnect();
                        System.exit(0);
                    }
                }
            });

            channel.connect(3 * 1000);

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

关于java - 通过 ssh 发送命令并读取输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20560240/

相关文章:

gitlab-shell : Disallowed command

Java J2SSH SFTP - 主机 key 无效

java - 在 Java 中接受来自外部文本文件的 SQL 查询

java - 在 IBM bluemix 中使用空间数据

java - Android 和 Eclipse - 通过 SVN 导出本地 jar

java - sshtools.SftpClient.put 失败,错误代码 "No such file"

java - j2ssh sshclient 不等待远程命令完成

java - JFace 向导传递变量

git - 在终端 SSH 中获取当前路径的 url

git - OpenSSH 提供了错误的公钥?