1

我需要一些帮助来修改我的脚本。它是为为一台设备完成相同的工作而编写的。我正在尝试以某种方式修改脚本,以便它检查 known_hosts 文件中的已知 ssh 密钥以获取 IP 地址列表。如果一个设备失败,它应该显示相应的错误并继续另一个设备。我正在从文件中播种 IP 地址。到目前为止,我拥有的代码类似于以下内容。

#!/bin/bash
#filename=test-file.txt
#while IFS= read -r ip in $filename
set +e
for ip in $(cat test-file.txt)
do
        echo $ip
        if [ -z "$ip" ]
        then
                echo " ERR - IP Adress not specified" #|| true
                #exit 1
        fi

        # Check if input is a valid IP address
        checkregex="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
        if [[ $ip =~ $checkregex ]]
        then
                echo "OK - Input is a valid IP address" #> /dev/null 2&>1
        else
                echo "ERROR - Invalid input" #|| true
        #exit 1
        fi

        # Get linenumber and remove the key from known_hosts file
        linenumber="$(egrep -m1 -n "$ip " /home/username/.ssh/known_hosts | cut -d':' -f1)"
        i=1
        while [ $i -gt 0 ]
        do
                if [ -z "$linenumber" ]
                then
                        echo "WARN - No stored SSH key found for this device" #> /dev/null 2&>1
                        i=0
                        #exit 0
                fi
                echo "OK - SSH key found at line number ${linenumber} - Going to remove it" #> /dev/null 2&>1
                sed -i "${linenumber} d" /home/username/.ssh/known_hosts
                echo "OK - Key removed - Retry config capture on the device"
                linenumber="$(egrep -m1 -n "$ip " /home/username/.ssh/known_hosts | cut -d':' -f1)"
                if [ -z "$linenumber" ]
                then
                        echo "OK - No more stored SSH key found for this device" #> /dev/null 2&>1
                        i=0
                fi
                done
                #exit 0
done #< $filename

我收到的输出类似于以下内容。

xx.xx.xx.xx (IP Address)
OK - Input is a valid IP address
WARN - No stored SSH key found for this device
OK - SSH key found at line number  - Going to remove it
OK - Key removed - Retry config capture on the device
OK - No more stored SSH key found for this device

如果我注释掉出口 1 或出口 0,它会持续进行。如果我不这样做,它会针对列表中的第一个 IP 执行并存在。

我尝试以多种方式修改脚本,但没有太大帮助(您可以看到我尝试过的许多评论条目)

在此先感谢您的帮助。

Soumyadipta Ganguly

4

0 回答 0