为使用JSch通过SSH执行的命令提供输入/子命令 [英] Providing input/subcommands to command executed over SSH with JSch

查看:364
本文介绍了为使用JSch通过SSH执行的命令提供输入/子命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to manage router via Java application using Jcraft Jsch library.

我正在尝试通过TFTP服务器发送Router Config。问题出在我的Java代码中,因为这适用于PuTTY。

I'm trying to send Router Config via TFTP server. The problem is in my Java code because this works with PuTTY.

这是我的Java代码:

This my Java code:

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

我得到


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

Line has an invalid autocommand '192.168.50.1'

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

The problem is how can I run those successive commands.

推荐答案

多次调用 ChannelExec.setCommand 无效。

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

And even if it had, I'd guess that the 192.168.50.1 : and Config.txt are not commands, but inputs to the copy run tftp : command, aren't they?

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

If that's the case, you need to write them to the command input.

这样的事情:

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

这篇关于为使用JSch通过SSH执行的命令提供输入/子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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