天天看點

Linux系統shell腳本程式設計――生産實戰案例!/bin/sh!/bin/sh

linux系統shell腳本程式設計――生産實戰案例

1、開發腳本前準備

一般大家都知道,測試主機是否線上,常用的指令無非就是ping、nmap,是以,首先找一個位址來測試下ping指令的效果

[root@centos6 scripts]# ping -w 2 -c 2 172.16.1.1

ping 172.16.1.1 (172.16.1.1) 56(84) bytes of data.

64 bytes from 172.16.1.1: icmp_seq=1 ttl=255 time=0.704 ms

64 bytes from 172.16.1.1: icmp_seq=2 ttl=255 time=0.481 ms

--- 172.16.1.1 ping statistics ---

2 packets transmitted, 2 received, 0% packet loss, time 1000ms

rtt min/avg/max/mdev = 0.481/0.592/0.704/0.114 ms<code>`</code>

這種方法可以實作,測試發送2個資料包,然後加上逾時時間,自動停止,可以達到效果

[root@centos6 scripts]# vi checkip.sh

. /etc/init.d/functions

cmd="ping -w 2 -c 2"

ip="172.16.1.2 172.16.1.3 172.16.1.100"

for n in $ip

do

$cmd $n &gt;/dev/null 2&gt;&amp;1

if [ $? -eq 0 ];then

action "$n is online" /bin/true

else

action "$ip$n is not online" /bin/false

fi

done

執行下腳本看看結果如何

[root@centos6 scripts]# sh checkip.sh

172.16.1.2 is online [ ok ]

172.16.1.3 is online [ ok ]

172.16.1.100 is not online [failed]<code>`</code>

此時肯定有小夥伴問了,你這個腳本測試的隻有三個ip,如果内網整個網段ip都手工寫上去,豈不是更費時費力,是以,如果是整個網段,那麼定義ip變量時可以定義成這樣ip="172.16.1." ,因為前三位是相同的,寫for 循環時可以修改成如下

[root@centos6 scripts]# nmap -sp 172.16.1.1

nmap scan report for 172.16.1.1

host is up (0.0091s latency).

mac address: 04:bd:70:fb:a9:b7 (unknown)

nmap done: 1 ip address (1 host up) scanned in 0.04 seconds

[root@centos6 scripts]# nmap -sp 172.16.1.100

note: host seems down. if it is really up, but blocking our ping probes, try -pn

nmap done: 1 ip address (0 hosts up) scanned in 0.41 seconds<code>`</code>

從上面的結果來看,很容易發現線上與不線上傳回的資訊不同,但是我們需要取得線上的ip位址資訊,那到就隻能取 nmap scan report for 172.16.1.1 ,因為所有線上的ip傳回的資訊中都會有這一行資訊,是以取相同的資訊。

[root@centos6 scripts]# nmap -ss 172.16.1.1|grep "open"

21/tcp open ftp

23/tcp open telnet

80/tcp open http

443/tcp open https

[root@centos6 scripts]# nmap -ss 172.16.1.1|grep "open"|awk '{print $1}'

21/tcp

23/tcp

80/tcp

443/tcp

[root@centos6 scripts]# vi checkip_namp01.sh

fcmd="nmap -sp "

ip="172.16.1.1 172.16.1.2 172.16.1.100"

tcmd="nmap -ss"

upip=<code>$fcmd $ip|grep "nmap scan report for"|awk '{print $5}'</code>

for ip in ${upip}

action "$ip is on line" /bin/true

#列印資訊

for port in ${upport}

done<code>`</code>

注:upport=<code>$tcmd $ip|grep "open"|awk '{print $1}'</code> 定義這個變量時,取的ip位址一定要是上一個循環取出的ip位址,否則會有問題

執行腳本,測試效果如何?

[root@centos6 scripts]# telnet 172.16.1.1 443

trying 172.16.1.1...

connected to 172.16.1.1.

escape character is '^]'.

^]

telnet&gt; quit

connection closed.

[root@centos6 scripts]# telnet 172.16.1.1 21

220 ftp service ready.

[root@centos6 scripts]# telnet 172.16.1.2 23

trying 172.16.1.2...

connected to 172.16.1.2.

tl-ap301c login:

connection closed.<code>`</code>

繼續閱讀