如何在 SSH 中成功地将此 bash 脚本调整为 运行 telnet 命令?

How to adjust this bash script to run telnet commands successfully while being in SSH?

我正在尝试编写一个 bash 脚本来执行以下工作流程:

  1. 通过端口 9100 上的 IP 地址远程登录到联网设备 telnet x.x.x.x 9100
  2. 运行 SGD 命令! U1 getvar \"internal_wired.ip.timeout.value\".
  3. 预计 "10" 的输出值。

这是我目前编写的 bash 脚本:

#!/bin/bash

IP=(x.x.x.x) 


    for i in ${IP}
    do
      echo " "
      echo "Welcome! This script will check the timeout value of this networked device."
      echo "The expected output should be `"10`". Let's get started!!"
      echo " "
      sleep 4
      echo "5....."
      sleep 1
      echo "4...."
      sleep 1
      echo "3..."
      sleep 1
      echo "2.."
      sleep 1
      echo "1."
      sleep 1
      echo " "
      telnet ${i} 9100 << END_SSH
        sleep 5
        getvar \"internal_wired.ip.timeout.value\"
        sleep 5
    END_SSH
    done

当我通过 bash mycode.sh 运行 这个脚本时,我在 Terminal.app 中得到以下输出:

$ bash mycode.sh 

Welcome! This script will check the timeout value of this networked device.
The expected output should be "10". Let's get started!!

5.....
4....
3...
2..
1.

Trying x.x.x.x...
Connected to x.x.x.x.
Escape character is '^]'.
Connection closed by foreign host.
[user@server ~]$ 

x.x.x.x是一个IP占位符,只是为了添加。

理论上,在Escape character is '^]'.行之后,脚本应该有运行 ! U1 getvar "internal_wired.ip.timeout.value\"命令。

此外,我们应该有 "10" 的预期输出。

当我第一次写这个脚本的时候,我最初并没有把END_SSH命令放在里面。一位同事向我介绍了这一点,并说要将 telnet 命令包装在 END_SSH 中,因为当您在 telnet 中时,终端技术上是如何跳出 SSH 的。我试过使用 END_SSH,但没有成功。

如何让 telnet 命令成功 运行 并获得预期的输出值?

你误解了"END_SSH"是什么。这不是 "command" - 它是 bash 中所谓的 "Here-document"。

本质上,<<END_SSHEND_SSH 之间的文本是一个 "here-document",它通过管道传输到 telnet ${i} 9100 的标准输入中。因此,sleep 5 命令从未真正执行过,甚至在连接建立之前输入就达到了 EOF。

我不知道你到底想完成什么,但我想下面的方法会更好。哦,那个奇怪的 IP=(x.x.x.x) 声明是怎么回事?那应该是一个数组吗?

#!/bin/bash

declare -a IP=(1.1.1.1 2.2.2.2 3.3.3.3 4.4.4.4)

for i in "${IP[@]}"; do
    echo " "
    echo "Welcome! This script will check the timeout value of this networked device."
    echo "The expected output should be \"10\". Let's get started!!"
    sleep 4
    for j in {5..1}; do
        echo $j
        sleep 1
    done

    { sleep 5; echo -n $'! U1 getvar "internal_wired.ip_timeout.value"\n'; sleep 5; } | telnet ${i} 9100
done

所以这是我建议用于 telnet 部分的内容。 Connect 是稍后在 while 循环中调用的函数,它将 运行 通过文件中准备好的 IP。

    Connect()
    {
    (
        sleep 10 # depending upon your network and device response, better to keep this first sleep value a little high

        echo "command 1"
        sleep 2
        echo "command 2"
       sleep 2
    ) | telnet  9100 | tee -a .log
    }

    while read -r IP 
    do 
       Connect $IP
    done < filewithIPs