我的要求是从 Node js连接到Telnet客户端。
我正在使用 telnet-client包裹
我正在使用此代码进行连接
var Telnet = require('telnet-client')
var connection = new Telnet()
var params = {
host: '127.0.0.1',
port: 23,
shellPrompt: '/ # ',
timeout: 1500,
// removeEcho: 4
}
connection.on('ready', function(prompt) {
connection.exec(cmd, function(err, response) {
console.log(response)
})
})
connection.on('timeout', function() {
console.log('socket timeout!')
connection.end()
})
connection.on('close', function() {
console.log('connection closed')
})
connection.connect(params)`
但它总是返回“套接字超时!”在控制台中。
我还尝试在参数中添加“用户名”和“密码”详细信息
`var params = {
host: '127.0.0.1',
port: 23,
shellPrompt: '/ #',
loginPrompt: 'Username: ',
passwordPrompt: 'Password: ',
username: 'vinit',
password: 'vinit123',
initialLFCR: true,
timeout: 1500,
// removeEcho: 4
}`
但仍然面临同样的问题。在某些链接中,我发现有人说 shellPrompt
值不正确,那么 shellPrompt
的值应该是多少。实际上我对这个话题完全陌生,所以对此不太了解。
任何帮助将不胜感激。提前致谢。
最佳答案
根据您的意见,这不是网络连接问题,这意味着您的连接在登录期间失败,或者之后无法检测到有效提示(然后等待直到超时)。
因此,您应该做的第一件事是添加 failedLogin
回调:
connection.on('failedlogin',function(msg) {
console.log("Login failed !",msg);
});
检测“登录失败”的情况(否则会尝试登录一次,然后挂起直到超时)。
接下来,“手动”连接到您的服务器,即从命令行运行 telnet 127.0.0.1
,然后查看“登录/密码”和“shell”提示的外观.
例如在我的“Ubuntu 16.04.3 LTS”系统上:
%telnet 127.0.0.1
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Ubuntu 16.04.3 LTS
zeppelin-desktop login: zeppelin
Password:
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.4.0-97-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
zeppelin@zeppelin-desktop:~$
- 登录提示是
zeppelin-desktop login:
- 密码提示为
密码:
- shell 提示符是
zeppelin@zeppelin-desktop:~$
登录和密码提示确实匹配它们在 telnet-client 中的预定义模式.
loginPrompt: Username/login prompt that the host is using. Can be a string or an instance of RegExp. Defaults to regex '/login[: ]*$/i'.
passwordPrompt: Password/login prompt that the host is using. Can be a string or an instance of RegExp. Defaults to regex '/Password: /i'.
所以没有必要改变它们。
Shell 提示不匹配预定义模式(/#
):
shellPrompt: Shell prompt that the host is using. Can be a string or an instance of RegExp. Defaults to regex '/(?:/ )?#\s/'.
所以需要修改,例如
shellPrompt: /:~[^$]*\$\s*$/,
你可以用 grep 测试你的 shell 提示模式,就像这样:
%echo 'zeppelin@zeppelin-desktop:~$' | grep -o ':~[^$]*\$\s*$'
:~$
(不匹配输出为空)
现在您已经有了正确的 shell 提示模式,telnet-client
应该能够识别它,并发送 cmd
(在 on(' ready')
handler) 到服务器,以响应它。
例如如果您设置 cmd="date"
,您应该得到当前日期作为响应:
connection.on('ready', function(prompt) {
console.log(">date");
connection.exec("date", function(err, response) {
console.log("<",response)
})
})
%nodejs telnet.js
>date
< Wed Oct 25 10:11:11 UTC 2017
附言
您可能想要设置的另一个选项是“登录失败”模式:
failedLoginMatch : "Login incorrect"
检测服务器拒绝您的密码。
这在我的 Ubuntu 系统上不是绝对必要的,因为它只会
在密码失败的情况下重复登录提示,以便 failedlogin
事件无论如何都会被调度,但取决于您的配置,
它可能是必需的。
关于node.js - 套接字超时!使用 Node telnet-client 的 Telnet 连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46743775/