sshpass在read循环中断Bash时传入



我正在尝试创建一个循环,为列表中的每个主机存储ssh命令的输出。

代码:

#!/bin/bash
while read i; do
ip=$(echo "$i" | awk -F ""*,"*" '{print $2}') #(file contains name,ip values)
if echo "$i" | grep -q "ARISTA"; then
results=$(sshpass -f/root/cred ssh user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "NEXUS"; then
results=$(sshpass -f/root/cred ssh user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "ARUBA"; then
results=$(sshpass -f/root/cred ssh user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "R1"; then
results=$(sshpass -f/root/cred ssh user@$ip "show configuration | display set")
echo "$results"
elif echo "$i" | grep -q "HP"; then
results=$(sshpass -f/root/cred ssh user@$ip "display current-configuration")
echo "$results"
else
echo "$i not found"
fi
done </root/hosts.txt

我得到的输出是列表中第一个主机的结果。我怀疑问题是sshpass,因为当我尝试不同的语句时,我收到了准确的结果,如:

#!/bin/bash
while read i; do
ip=$(echo "$i" | awk -F ""*,"*" '{print $2}') #(file contains name,ip values)
if echo "$i" | grep -q "ARISTA"; then
echo "$ip = Arista"
elif echo "$i" | grep -q "NEXUS"; then
echo "$ip = Nexus"
elif echo "$i" | grep -q "ARUBA"; then
echo "$ip = Aruba"
elif echo "$i" | grep -q "R1"; then
echo "$ip = R1"
elif echo "$i" | grep -q "HP"; then
echo "$ip = HP"
else
echo "$i not found"
fi
done </root/hosts.txt

然而,在执行第一个sshpass命令之后,循环就中断了。

有什么想法吗?

好的。

这就是解决方案:

#!/bin/bash
while read i; do
ip=$(echo "$i" | awk -F ""*,"*" '{print $2}') #(file contains name,ip values)
if echo "$i" | grep -q "ARISTA"; then
results=$(sshpass -f/root/cred ssh -n user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "NEXUS"; then
results=$(sshpass -f/root/cred ssh -n user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "ARUBA"; then
results=$(sshpass -f/root/cred ssh -n user@$ip "show running-config")
echo "$results"
elif echo "$i" | grep -q "R1"; then
results=$(sshpass -f/root/cred ssh -n user@$ip "show configuration | display set")
echo "$results"
elif echo "$i" | grep -q "HP"; then
results=$(sshpass -f/root/cred ssh -n user@$ip "display current-configuration")
echo "$results"
else
echo "$i not found"
fi
done </root/hosts.txt

解释正如Jetchill所建议的,ssh正在吃STDIN。因此,解决方案将标志-n添加到ssh命令中,该命令将把输出传递给/dev/null。

非常感谢各位,祝你们好运。

最新更新