我需要找到一種方法來自動執行到我的路由器的ssh命令。我的目標是在我從Java程序運行腳本時重新啓動路由器。我有一些問題,但。需要自動執行SSH命令到路由器
首先,這是輸出的順序,我從我的路由器的SSH得到:返回
ssh [email protected]
: 首先,我做
[email protected]'s password:
我輸入密碼,「管理」。接下來到了這樣的提示:
Welcome Visiting Huawei Home Gateway
Copyright by Huawei Technologies Co., Ltd.
Password is default value, please modify it!
WAP>
現在,我輸入「復位」,它重新啓動路由器。
我已經嘗試了Tcl和Expect,雖然我可以在Windows上工作,但它在Linux上不起作用。這是我針對Tcl腳本代碼:
#!/bin/sh
# \ exec tclsh "$0" ${1+"[email protected]"}
package require Expect
spawn ssh [email protected]
send "admin\r"
send "reset\r"
after 3000
exit
每當我試着執行它,Tcl8.6貫穿它並終止,而無需實際做任何事情。但是,如果我在運行Tcl8.6時手動輸入所有這些命令,那麼它工作得很好。
我也試過了JSch Java庫。因此,我可以讓Java程序連接並輸出路由器的外殼,但是我嘗試發送的任何命令都不會執行任何操作。下面是該代碼:
...
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";
但它做同樣的事情。任何人都知道我可以做到這一點嗎?
我剛剛注意到你的命令以'\ r'結尾。試試'\ n',看看它是否適合你。 – vempo