如何添加变量匹配主机名

问题描述 投票:0回答:1

我试图制作一个期望脚本登录到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 $1}'`; 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必须与脚本连接的主机匹配。

我用ssh测试这个到不同的linux主机,然后我执行脚本到一个实时的cisco环境,我将使用telnet连接,但功能应该是相同的。

bash expect
1个回答
0
投票

对于.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
© www.soinside.com 2019 - 2024. All rights reserved.