您的位置:首页 > 编程语言 > Python开发

netstat获取服务器外部连接IP并过滤出非本地服务器程序有关联的IP脚本

2017-06-22 17:44 621 查看
#!/bin/env python
#-*- coding:utf-8 -*-
import os
import sys
from subprocess import Popen
def get_foriegn_ip():
l = os.popen("netstat -ant|grep ESTABLISHED|awk '{print $5}'|awk -F: '{print $1}'|sort -r|uniq -c |awk '{print $2}'|grep -v 'and'|grep -v 'Address'|grep -v '0.0.0.0' > foreign_ip.txt")
def list_different():
list1=[]
f = open('foreign_ip.txt','r')
for line in f.readlines():
line1=line.replace("\n","")
list1.append(line1)
print(list1)
list2=[]
f = open('localgroup.txt','r')
for line in f.readlines():
line1=line.replace("\n","")
list2.append(line1)
print(list2)
l = [x for x in list1 if x not in list2]
print(l)
def get_time():
d = os.popen('echo "$(date +%Y%m%d_%H:%M:%S)">>/root/1.txt')
if __name__ == '__main__':
get_foriegn_ip()
list_different()
get_time()
说明:
1,在将服务器所处集群相关联的IP写入文档localgroup.txt;
2,将脚本写入crontab中 python huangyishan.py >> ./1.txt
3,定时任务执行的时候写入一个时间到文档1.txt;
4,get_foriegn_ip函数根据自己想要的实际效果灵活修改;
5,此脚本是在data目录中执行的,大家可以随意更改;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐