shell脚本从多个服务器查找IP地址

时间:2020-03-05 15:31:43  来源:igfitidea点击:

在本教程中,我们了解如何编写Shell脚本以查找来自多个Linux服务器的IP地址。
在服务器上做一些审计时,这非常有用。

shell脚本可用于查找从多个服务器分配的以太网接口详细信息和IP地址/网络掩码。

即使没有设置IP地址,脚本也将显示接口名称。
确保我们拥有授权键设置,因此每个服务器都可以使用SSH登录而无需密码。

shell脚本获取IP地址

在以下脚本中,'server_list.txt'文件保留服务器列表,"结果.txt"文件包含具有servername和IP详细信息的所有输出。

#!/bin/bash
#we save to variable name of file with list of server
serverlist='server_list.txt'
#we save to variable list of servers from file
servers=`cat $serverlist`
#we save in variable name of file with results
result='result.txt'
#we get each server from servers variable
for server in $servers
do
#Printing servername to result file
echo -e "$server"> $result
#getting list of ethernet links via ifconfig command, and from all output we need onlu lines that have word link and starting with [a-z][a-z]*[0-9], and after we get first word from output
ips=`ssh root@${server{ "ifconfig -a | grep -o -e '[a-z][a-z]*[0-9]*[ ]*Link' |grep -v lo| perl -pe 's|^([a-z]*[0-9]*)[ ]*Link||'"`
After for every ethernet link from ips variable
for ip in $ips
do
#we get ips, via ifconfig command, and grepping for inet addr script.
INET=`ssh root${server} "ifconfig $ip |grep -o -e 'inet addr:[^ ]*' | grep -o -e '[^:]*$'"`
#same for mask
MASK=`ssh $server "ifconfig $ip |grep -o -e 'Mask:[^ ]*' | grep -o -e '[^:]*$'"`
#this check if any ip assigned
if [ -x $INET ];
then
#if no ip we will get no ip address set
INET="no ip address set"
fi
#we check if we get mask
if [ -x $MASK ];
then
MASK="no mask address set"
fi
#and we put result to result file.
echo "$ip : $INET : $MASK" >> $result
done
#this print empty line to result file
echo “” >> $result
done

示例输出

Server1#./ifconfig.sh.sh
Server1#cat result.txt
red
eth0 : 91.197.140.34 : 255.255.255.0
eth1 : 192.168.33.34 : 255.255.255.0
venet0 : no ip address set