最近公司要清洗一下服务器的ip使用情况,需求如下:

1,统计所有服务器的内外网ip使用情况(结合业务),找出释放ip

2,批量操作近500台左右的服务器,进行统计

服务器ip校验初步开始:

#!/bin/python

#-*- coding:utf-8 –*-

import os

import socket,fcntl,struct

#获取ip a和hostname

def get_iphn():

global  Inner_ip,Outer_ip

Inner_ip = os.popen("ifconfig |grep 'inet'|grep -v '127.0.0.1'|grep -v 'inet6'|awk '{print $2}'|grep  '^10.*'").read()

        Outer_ip = os.popen("ifconfig |grep 'inet'|grep -v '127.0.0.1'|grep -v 'inet6'|awk '{print $2}'|grep -v '^10.*'|grep -v '^172*'").read()

        hostname = os.popen("hostname").read()

        print "主机名位:\n",hostname

        print "内网ip为:\n",Inner_ip

        print "公网ip为: \n",Outer_ip

#获取网卡配置ip

def net_ip():

network = os.popen("cat /etc/sysconfig/network-scripts/ifcfg-*|grep IPADDR|awk -F '=' '{print $2}'|grep -v '127.0.0.1'").read()

print "网卡配置的全部ip为:\n",network

#没有内网的机器

line = os.popen("ifconfig |grep 'inet'|grep -v '127.0.0.1'|grep -v 'inet6'|awk '{print $2}'|grep  '^10.*'|wc -l").read()

print "开始检测网卡配置是否正确。。。"

if  Inner_ip  in network :

if line == 0:

print "内网配置不正确"

else:

print "内网配置正确"

if Outer_ip in network:

print "公网配置正确"

else:

print "公网配置不正确"

#获取指定网卡ip(用于网卡名称不一致)

def get_ip2(ifname):  

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  

    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) 

#调用模块

#if  __name__ == '__main__':

#get_ip2('lo')

get_iphn()

net_ip()