通过SSH发送命令并读取输出结果 [英] Send command via ssh and read ouput results

查看:280
本文介绍了通过SSH发送命令并读取输出结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have code to connect to a remote server via ssh and send 2 or more commands to it (for example: cd /export/home/ops/bin and "./viewlinkload –time 20131205-19") but I don't see the command executed and don't receive results.

我需要从服务器返回结果并显示它.

I need to get the result returned from server and display it.

这是代码发送命令:

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

如果i Change命令为"ls \ n",则最后一条记录在"while((line = bufferedReader.readLine())!= null)"处挂起并且不运行. 帮我. 谢谢大家.

If i Change command is "ls\n" After the last record is suspend at "while ((line = bufferedReader.readLine()) != null)" and don't run. Help me. Thanks all.

推荐答案

Jsch在examples目录中有一些出色的示例,您可能会感兴趣的一个特别的示例称为Exec.您可能也对Shell

Jsch has some excellent examples in the examples directory, the one in particular you might find of interest is called Exec. You might also be interested in Shell

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

This is a slightly modified version which skips getting the information from the command line and prompting for the user info and command and simply attempts to connect directly to the remote machine and execute a ls command.

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);
        }
    }
}

我在连接到Mac盒之一的Windows盒上进行了测试,没有任何问题

I tested this on my Windows box connecting to one of my Mac boxes without any issues

已更新了被黑的Shell示例

基本上,这是一个基于Shell示例的被黑示例.

Basically, this is a hacked example based on the Shell example.

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

This uses a custom OutputStream to monitor changes to the content being sent from the remote machine and which can issue commands. This is pretty basic, in the fact that all I'm doing is waiting for $ to be send to the output stream and then issuing the next command.

修改它不需要太多的工作,因此,根据当前的命令/命令索引,您可以进行不同的解析...

It wouldn't take too much work to modify it so that, based on the current command/command index, you could do different parsing...

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);
        }
    }
}

这篇关于通过SSH发送命令并读取输出结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆