利用Python实现跨平台网卡信息采集的工具

  本代码实现特点:

    1. 可以跨平台,无论是Linux还是Windows,在实例初始化的时候,首先判断目标的操作系统类型,不同的操作系统要执行的shell命令不一样。

    2. 由于Windows的ipconfig命令不能像Linux 的ifconfig命令可以指定网卡显示相关信息,因此这里需要依赖正则表达式对相关信息的提取,比如IP地址,MAC地址

 

  1 import subprocess
  2 import os
  3 import sys
  4 import termcolor
  5 import re
  6 
  7 class NetworkInterfaces:
  8     def __init__(self) -> None:
  9         self.os_type = self.check_os()
 10 
 11     def program_info(self):
 12         info = """
 13             ****************************************************************************************
 14             *************************Network information tool by Jason wong*************************
 15             ****************************************************************************************
 16             Menu:
 17                 1 Display interfaces list on the machine
 18                 2 Display IP addresses and netmask                
 19                 3 quit
 20         """
 21         print(info)
 22 
 23     def display_interfaces(self):
 24         
 25         try:
 26             if self.os_type == 'posix':
 27                 command = "ifconfig | grep flags | awk '{print $1}' | cut -d ':' -f 1 | grep -v 'lo'"
 28                 result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8')
 29                 interfaces_list = result.split('\n')[0:-1]            
 30                 return interfaces_list
 31             else:
 32                 result =  subprocess.check_output('ipconfig',shell=True, encoding='gbk',stderr=subprocess.STDOUT)   这里需要需要指定encoding为gbk
 33                 interfaces_list = re.findall(r'(?:以太网适配器\s*)(.*):',result)
 34                 return interfaces_list
 35         except Exception as e:
 36             print("Error happened in the module of display_interfaces", e)
 37             sys.exit(0)
 38 
 39     def check_os(self):
 40         return os.name
 41     
 42 
 43     def display_ipaddr(self):
 44         try:
 45             if self.os_type == 'posix':
 46                 interface = input("[-] Enter interface: ").strip()
 47                 command = "ifconfig %s | grep 'inet ' | awk '{print $2, $4}'" % interface   #特别注意,这里不能用format字符串,否则会报错
 48                 result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT).decode('utf-8')
 49                 ipaddr, netmask,nullvalue = re.split(r'\s', result)
 50                 
 51                 return ipaddr, netmask
 52 
 53             else:
 54                 interface = input("[-] Enter interface: ").strip()
 55                 result1 = subprocess.check_output('ipconfig',shell=True, encoding='gbk',stderr=subprocess.STDOUT)
 56                 pattern1 = r"(?:{}:)(.*?)(?:以太网适配器)".format(interface)
 57                 result2 = re.search(pattern1,result1,re.DOTALL).group()
 58                 pattern2 = r"(?:IPv4\s地址.*:\s*)(.*)"
 59                 ipaddr = re.search(pattern2, result2).group(1).strip()
 60                 
 61                 pattern3 = r"(?:子网掩码.*:)(.*)"
 62                 netmask = re.search(pattern3, result2).group(1).strip()
 63                 return ipaddr, netmask
 64 
 65 
 66         except Exception as e:
 67             print("Error happened in the module of display_ipaddr", e)
 68             sys.exit(0)
 69 
 70 
 71         
 72 
 73   
 74 
 75     def run(self):
 76         self.program_info()
 77         while True:
 78             choice = input("[-] Enter your choice: ")
 79 
 80             if choice == '1':
 81                 interfaces_list = self.display_interfaces()
 82                 print("Interfaces list as follows:\n")
 83                 for interface in interfaces_list:
 84                     print(interface)
 85 
 86             elif choice == '2':
 87                 ipaddr, netmask = self.display_ipaddr()
 88                 print("IP Address: %s" % ipaddr)
 89                 print("Netmaks: %s" % netmask)
 90 
 91      
 92             elif choice == '3':
 93                 break
 94             else:
 95                 print(termcolor.colored("Invalid input", 'red'))
 96                 continue
 97 
 98 if __name__ == "__main__":
 99     networkinterface = NetworkInterfaces()
100     networkinterface.run()

 

posted @ 2022-05-25 13:56  Jason_huawen  阅读(103)  评论(0编辑  收藏  举报