需要将SSH命令自动化到路由器

时间:2016-08-13 09:17:32

标签: java linux ssh tcl jsch

我需要找到一种方法来自动化ssh命令到我的路由器。我的目标是每当我从Java程序运行脚本时重启路由器。我有一些问题。

首先,这是我从路由器的ssh获得的输出序列: 首先我做:

ssh root@192.168.100.1

返回:

root@192.168.100.1's password: 

我输入密码“admin”。然后转到此提示:

Welcome Visiting Huawei Home Gateway
Copyright by Huawei Technologies Co., Ltd.

Password is default value, please modify it!
WAP>

现在,我输入“reset”并重新启动路由器。

我已经尝试了Tcl和Expect,虽然我可以在Windows上使用它,但它在Linux上不起作用。这是我的Tcl脚本代码:

#!/bin/sh
# \ exec tclsh "$0" ${1+"$@"}
package require Expect
spawn ssh root@192.168.100.1
send "admin\r"
send "reset\r"
after 3000
exit

每当我尝试执行它时,Tcl8.6都会通过它运行并在没有实际执行任何操作的情况下终止。但是,如果我在运行Tcl8.6时手动输入所有这些命令,它可以正常工作

我也尝试过JSch Java库。有了这个,我可以让Java程序连接并输出路由器的shell,但是我尝试发送的任何命令都没有。这是以下代码:

    ...
JSch jsch = new JSch();

        Session session = jsch.getSession("root", "192.168.100.1", 22);

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

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

        String command = "reset\r";

        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();
        System.out.println("disconnected");

这是我得到的输出:

Connect to session...

Welcome Visiting Huawei Home Gateway
Copyright by Huawei Technologies Co., Ltd.

Password is default value, please modify it!
WAP>

直到我退出才停留在这里。路由器不会重启。我也试过了:

String command = "reset";

但它做同样的事情。有谁知道我能做到这一点吗?

1 个答案:

答案 0 :(得分:4)

尝试使用 shell 代替 exec 与设备进行交互。

以下是我过去常用的快速代码,您可以根据自己的需要进行调整:

private static final String PROMPT = ">";

public static void main(String[] args) throws Exception {

    Session session = null;
    ChannelShell channel = null;

    try {

        JSch jsch = new JSch();
        session = jsch.getSession("root", "192.168.100.1", 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword("admin");
        session.connect();

        channel = (ChannelShell) session.openChannel("shell");

        PipedOutputStream reply = new PipedOutputStream();
        PipedInputStream input = new PipedInputStream(reply);
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        channel.setInputStream(input, true);
        channel.setOutputStream(output, true);

        channel.connect();

        getPrompt(channel, output);
        writeCommand(reply, "reset");
        getPrompt(channel, output);

    } finally {

        if (channel != null) {
            channel.disconnect();
        }

        if (session != null) {
            session.disconnect();
        }
    }
}

private static void writeCommand(PipedOutputStream reply, String command) throws IOException {
    System.out.println("Command: " + command);
    reply.write(command.getBytes());
    reply.write("\n".getBytes());
}

private static void getPrompt(ChannelShell channel, ByteArrayOutputStream output)
        throws UnsupportedEncodingException, InterruptedException {

    while (!channel.isClosed()) {

        String response = new String(output.toByteArray(), "UTF-8");
        System.out.println(response);
        if (response.trim().endsWith(PROMPT)) {
            output.reset();
            return;
        }

        Thread.sleep(100);
    }
}

更新:我注意到您通过SSH发送的命令以\r结尾。请尝试\n,看看它是否适合您。