【问题标题】:Providing input/subcommands to command executed over SSH with JSch使用 JSch 为通过 SSH 执行的命令提供输入/子命令
【发布时间】:2017-08-17 06:27:40
【问题描述】:

我正在尝试使用 Jcraft Jsch 库通过 Java 应用程序管理路由器。

我正在尝试通过 TFTP 服务器发送路由器配置。问题出在我的 Java 代码中,因为它适用于 PuTTY。

这是我的 Java 代码:

int port=22;
String name ="R1";
String ip ="192.168.18.100";
String password ="root";

JSch jsch = new JSch();
Session session = jsch.getSession(name, ip, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");

ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

InputStream in = channelExec.getInputStream();
channelExec.setCommand("enable");

channelExec.setCommand("copy run tftp : ");
//Setting the ip of TFTP server 
channelExec.setCommand("192.168.50.1 : ");
// Setting the name of file
channelExec.setCommand("Config.txt ");

channelExec.connect();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int index = 0;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
    System.out.println(line);
}
session.disconnect();

我明白了

行有一个无效的自动命令'192.168.50.1'

问题是如何运行这些连续的命令。

【问题讨论】:

    标签: java ssh router jsch cisco


    【解决方案1】:

    多次调用ChannelExec.setCommand没有效果。

    即使有,我猜192.168.50.1 : Config.txt 不是命令,而是copy run tftp : 命令的输入,不是吗?

    如果是这种情况,您需要将它们写入命令输入。

    类似这样的:

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channelExec.setCommand("copy run tftp : ");
    OutputStream out = channelExec.getOutputStream();
    channelExec.connect();
    out.write(("192.168.50.1 : \n").getBytes());
    out.write(("Config.txt \n").getBytes());
    out.flush();
    

    一般来说,检查命令是否有更好的“API”总是比输入命令更好。命令通常具有命令行参数/开关,可以更好地满足预期目的。


    一个相关问题:Provide inputs to individual prompts separately with JSch

    【讨论】:

    • 非常感谢。现在可以使用了。
    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    相关资源
    最近更新 更多