我正在尝试编写一个 bash 脚本,通过 SNMPv3 收集信息并为给定设备生成配置模板。
我的目标是根据变量生成模板mib 编号 X和接口X其中 X 是由用户输入确定的数字(例如,您想要添加多少个接口?接口的名称是什么?)
#!/bin/bash
# Ambiguously defined variables for the sake of demonstration:
authpriv="authPriv"
devicetype="ASA"
snmpuser="username"
authhash="SHA"
authstring="authpassword"
privhash="AES"
privstring="privpassword"
ipaddress="1.1.1.1"
interface1="Inside"
interface2="Outside"
numberofifs="2"
defaultasa="yes"
# Determine how many interfaces are to be added and what their friendly names are
if [[ $defaultasa = "yes" ]];
then
read -p "How many interfaces would you like to add to monitoring for this device? " numberofifs
for ((i = 1; i <= numberofifs; i++))
do
read -p "Please enter the name of interface number ${i} and press [ENTER]: " interface${i}
done
fi
# Walk the ifDescr MIBs, grep with the friendly name of the interface(s) and store the last number of IF-MIB::ifDescr.16 in *mibnumberX*.
if [[ $authpriv = "authPriv" ]] && [[ $devicetype = "ASA" ]];
then
for ((i = 1; i <= numberofifs; i++))
do
eval "ifnumber=\$interface$i"
eval "mibnumber$i=$(snmpwalk -v3 -u $snmpuser -l AuthPriv -a $authhash -A $authstring -x $privhash -X $privstring $ipaddress ifD | grep -i $ifnumber | awk -F"[<.=>]" '{print $2}')"
done
fi
# Display interface names and MIBs
printf "Name: $interface1\n MIB number: $mibnumber1\nName: $interface2\n MIB Number: $mibnumber2\n"
脚本结果:
$ ./test.sh
Name: Inside
MIB number: 15
Name: Outside
MIB Number: 16
目的是循环mib 编号 X和接口X变量并打印出下面的模板,其中散布着这些变量,无论添加了两个接口还是两百个接口。
if [[ $authpriv = "authPriv" ]];
then
for ((i = 1; i <= numberofifs; i++))
do
printf "\ndefine service{
service_description Interface $interface$i
check_command check_snmp_V3-2!$snmpuser!$authstring!$privhash!$privstring!$authpriv!$authhash!.1.3.6.1.2.1.2.2.1.8.$mibnumber${i}!-r 1 -m RFC1213-MIB!-l Interface \n} \n\n"
done
fi
然而,本节的输出却没有提供这样的运气:
$ ./test.sh
Name: Inside
MIB number: 15
Name: Outside
MIB Number: 16
define service{
service_description Interface 1
check_command check_snmp_V3-2!username!authpassword!AES!privpassword!authPriv!SHA!.1.3.6.1.2.1.2.2.1.8.1!-r 1 -m RFC1213-MIB!-l Interface
}
define service{
service_description Interface 2
check_command check_snmp_V3-2!username!authpassword!AES!privpassword!authPriv!SHA!.1.3.6.1.2.1.2.2.1.8.2!-r 1 -m RFC1213-MIB!-l Interface
}
我是一名正在尝试使用 bash 的新手,愿意接受任何建议。
答案1
如果有无限数量的可能条目,则应使用Bash 的数组作为数据结构,而不是为每个条目引入一个新变量。
您需要做的就是将要求输入姓名的行替换为以下内容(为便于阅读,文本已缩短):
read -p "Please enter the name … press [ENTER]: " interface[$i]
现在,$interface
将是一个包含接口名称的数组。您可以使用典型for
循环遍历条目,其中${interface[@]}
扩展到所有条目:
for name in "${interface[@]}"; do echo "$name"; done
您还可以轻松地在循环中使用它来访问索引处的for ((…))
数组元素,就像我们分配名称时所做的那样。$i
$interface[$i]