如何添加变量匹配主机名

How to add variable matching hostname

我正在尝试制作一个 expect 脚本来登录到 cisco 主机列表并执行一个命令,其中包含一个变量,该变量是与主机匹配的 ip 地址。

我有一个文件 (host_list),其主机名和 IP 地址格式如下:

host1.someplace.com 192.168.0.1
host2.otherplace.com 192.168.0.2
host3.thisplace.com 192.168.0.3
etc

.sh 脚本如下所示:

#!/bin/bash
 # Collect the current user's ssh password file to copy.
 echo -n "Enter the SSH password for $(whoami) : "
 read -s -e password
 echo -ne '\n'
 echo -n "Enter the command  : " 
 read -e command
 echo -ne '\n'

for device in `cat host_list | awk '{print }'`; do 
./configure-cisco.exp $device $password "$command" ;
 done

.exp 脚本:

#!/usr/bin/expect -f

# Set variables
 set hostname [lindex $argv 0]
 set username $env(USER)
 set password [lindex $argv 1]
 set command  [lindex $argv 2]
 set timeout 1
# Log results
 log_file -a ~/log/results.log

# Announce which device we are working on and at what time
 send_user "\n"
 send_user ">>>>>  Working on $hostname @ [exec date] <<<<<\n"
 send_user "\n"

 spawn ssh $hostname
 expect "password:"
 send "$password\n"
 expect "*$"
 send "$command\n"
 expect "*$"
 exit

我需要的是将 ip 地址与主机相匹配,并将其放入一个变量中以供 send "$command\n"

类似于:send "$command $ipaddress\n"

$command 随着时间的推移会有所不同,但在实际情况下会有所不同。

event manager environment PRIMARY_BGP_NEIGHBOR

并且 $ipaddress 必须与脚本连接的主机相匹配。

我在对实时 cisco 环境执行脚本之前使用 ssh 连接到不同的 linux 主机进行了测试,我将在其中使用 telnet 进行连接,但功能应该是相同的。

对于 .sh:

names=()
ips=()
n=0
while read name ip; do
  [[ -z $ip ]] && continue
  names[n]=$name
  ips[n]=$ip
  ((++n))
done < hostfile

for ((i=0; i<n; ++i)); do
  script.exp ${names[i]} ${ips[i]} $device "$passwd"
done