应用需求:执行netstat命令后,检查3121至3127端口是否有来自www.itkylin.com的连接,如果其中端口没有连接,则做出提示,如下图:
[email protected]:~# netstat -a|grep www.itkylin.com|grep :31 |grep ESTABLISHED

实现流程:将指定的ESTABLISHED端口通过split切片后通过list.append添加到list列表里,然后用固定要检查的端口列表for循环查询指定的端口是否有在list列表里,如果list列表里没有指定的端口,说明没有ESTABLISHED连接,则做出提示。
实现代码:
[email protected]:~# vi checkports.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #coding=utf-8
import os
os.system("netstat -an|grep :31 |grep ESTABLISHED > /root/pyend")
list = []
file = open("/root/pyend")
for line in file:
line_split_first = line.split()
#print (line_split_first[3])
line_split_second = line_split_first[3].split(':')
#print (line_split_second[1])
list.append(int(line_split_second[1]))
#print (list)
list_check_port = [3120,3121,3122,3123,3124,3125,3126,3127]
for temp in list_check_port:
if temp not in list:
print("port %d is not in the list!"%temp)
#else:
# print("port %d is in the list!"%temp)
file.close() |
[email protected]:~# python3 checkports.py