如何在脚本中使用telnet?

How to use telnet in a script?

我需要连接到一个系统,我必须先通过 SSH 然后通过 telnet。然后我可以开始执行一些命令。 我在 telnet 部分苦苦挣扎。你能告诉我怎么做吗?请问除了 spawn 还有其他选择吗?谢谢

#!/bin/bash
cat command.sh | sshpass -p 'passowrd' ssh -q -o StrictHostKeyChecking=no root@pc1;

然后我的command.sh

#!/bin/bash
spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;

在此使用中,shebang 无效*。您将脚本文件的内容传递给 ssh 以逐行执行,就好像每一行都是单独的命令,将由 shell 而不是 expect.

解释

尝试将 command.sh 更改为:

# no shebang here
/bin/expect -f - <<<'spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;'

这会将 expect 脚本作为 这里的字符串 发送到 expect 的 STDIN。如果您在 expect 脚本中使用变量,您可能需要更改引用或转义,具体取决于它们是 shell 还是 TCL 变量以及需要进行替换的位置。

* 当文件被标记为可执行时,内核使用 shebang select 程序来解释文件的内容,并且 运行 通过按名称调用文件.当文件 运行 通过显式命名解释器(例如 sh run_messh user@host run_me_there)时,shebang 不会发挥作用。

我找到了答案并且完美运行:

/bin/expect <<<'spawn telnet pc_modem 
expect "login:"
send "root\r"
expect "Password: ";
send "youyou\r"

send "yourcommand1\r"
send "yourcommand2\r"

expect eof
'