如何通过telnet连接到vyos路由器并发送命令?

时间:2019-04-29 09:39:34

标签: java telnet

我已经设法通过Java连接到vyos路由器,但是我无法自动发送命令。到目前为止,这是我的工作

import java.io.InputStream;
import java.io.PrintStream;

import org.apache.commons.net.telnet.TelnetClient;

public class telnetco {

    private TelnetClient telnet = new TelnetClient();
    private InputStream in;
    private PrintStream out;
    private String prompt = "$";

    public telnetco(String user, String password) {
        try {
            // Connect to the specified server
            telnet.connect("192.168.5.5", 22);

            // Get input and output stream references
            in = telnet.getInputStream();
            out = new PrintStream(telnet.getOutputStream());

            // Log the user on
            readUntil("login: ");
            write(user);
            readUntil("Password: ");
            write(password);

            // Advance to a prompt
            readUntil(prompt + " ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String readUntil(String pattern) {
        try {
            char lastChar = pattern.charAt(pattern.length() - 1);
            StringBuffer sb = new StringBuffer();
            boolean found = false;
            char ch = (char) in.read();
            while (true) {
                System.out.print(ch);
                sb.append(ch);
                if (ch == lastChar) {
                    if (sb.toString().endsWith(pattern)) {
                        return sb.toString();
                    }
                }
                ch = (char) in.read();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void write(String value) {
        try {
            out.println(value);
            out.flush();
            System.out.println(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String sendCommand(String command) {
        try {
            write(command);
            return readUntil(prompt + " ");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void disconnect() {
        try {
            telnet.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            telnetco telnet = new telnetco("vyos", "vyos");
            telnet.sendCommand("ping");
            telnet.sendCommand("conf");
            telnet.sendCommand("show");


            telnet.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}    

前两个命令有效,但是当我处于配置模式时,命令show不起作用。

0 个答案:

没有答案