0. Preface
Under normal circumstances, if you want to view the IP address or MAC address of the computer's network card, you can directly find the network card through the interface to view it, or you can get IP and other information through commands such as ifconfig of linux. This section teaches you how to obtain the IP/MAC information of the network card through python.
1. Test environment and key code interpretation
1.1 test environment
1.1.1 system:
Ubuntu 16.04.6 LTS Windows 10 x64
1.1.2 development tools:
pycharm professional edition Note: the professional edition supports local and remote linux Debugging.
2. Module introduction and demonstration
Only three modules are needed this time, but it's also very laborious.
- netifaces / / it needs to be installed. It is mainly used to obtain the network card interface IP/MAC and other information;
- winreg / / a built-in module, which is mainly used for Windows system to obtain the network card interface key value through the registry;
- platform / / built-in module, which is mainly used to judge the system type, such as windows, Linux, MacOS, etc;
2.1 example of platform module
Linux system:
import platform platform.system() 'Linux' #Return results
Windows system:
import platform platform.system() 'Windows' #Return results
2.2 use examples of netifaces module
For the installation method of external module, please refer to the Internet and ignore it here (very simple).
Usage: used to collect information such as network interface (IP / address / gateway).
The netiface module defines three functions:
def gateways(*args, **kwargs): #Get gateway Code block def ifaddresses(*args, **kwargs): #Get IP information Code block def interfaces(*args, **kwargs): #Get interface ID Code block
First look at the address family:
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- #Welcome to WeChat official account: drip Technology #The following is a demonstration in Linux environment from netifaces import pprint pp = pprint.PrettyPrinter(indent=4) #Using pprint output here will be more intuitive pp.pprint(netifaces.address_families) #Return result: { 0: 'AF_UNSPEC', 1: 'AF_FILE', 2: 'AF_INET', #ipv4 address 3: 'AF_AX25', 4: 'AF_IPX', 5: 'AF_APPLETALK', 6: 'AF_NETROM', 7: 'AF_BRIDGE', 8: 'AF_ATMPVC', 9: 'AF_X25', 10: 'AF_INET6', #ipv6 address 11: 'AF_ROSE', 12: 'AF_DECnet', 13: 'AF_NETBEUI', 14: 'AF_SECURITY', 15: 'AF_KEY', 16: 'AF_NETLINK', 17: 'AF_PACKET', #MAC address of ipv4 18: 'AF_ASH', 19: 'AF_ECONET', 20: 'AF_ATMSVC', 22: 'AF_SNA', 23: 'AF_IRDA', 24: 'AF_PPPOX', 25: 'AF_WANPIPE', 31: 'AF_BLUETOOTH'} #Here we focus on the following: AF_NET,AF_NET6 #Others, let's study it by ourselves
2.2.1 how to obtain the information of network card port in Linux Environment
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- #Welcome to WeChat official account: drip Technology import netifaces import pprint pp = pprint.PrettyPrinter(indent=4) netifaces.interfaces() ['lo', 'ens32'] #The returned result is the network card ID of the ubuntu system pp.pprint(netifaces.ifaddresses('ens32')) #The returned result is a dictionary with nested lists, so pay attention to slicing { 2: [ { 'addr': '192.168.0.253', 'broadcast': '192.168.0.255', 'netmask': '255.255.255.0'}], 10: [ { 'addr': 'fe80::20c:29ff:fe5d:2f55%ens32', 'netmask': 'ffff:ffff:ffff:ffff::/64'}], 17: [{'addr': '00:0c:29:5d:2f:55', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]} netifaces.ifaddresses('ens32')[netifaces.AF_INET][0]['addr'] '192.168.0.253' #Return the result and get the IPv4 address netifaces.ifaddresses('ens32')[netifaces.AF_PACKET][0]['addr'] '00:0c:29:5d:2f:55' #Return the result and get the IPv4 MAC address netifaces.ifaddresses('ens32')[netifaces.AF_INET6][0]['addr'] 'fe80::20c:29ff:fe5d:2f55%ens32' #Return the result and get the IPv6 address
2.2.2 how to obtain the information of network interface in Windows Environment
Note: the value of windows is much more complex than that of Linux. You can't directly obtain the IP information according to the interface. You need to find a string of unique key values first, and then you can obtain the interface IP information according to it. Here I give an example to avoid confusion:
My wireless card information:
Wireless network card name: WLAN
The corresponding key value on the registry: {CD94297B-D746-4494-91F7-3E40C091A0FC} //python needs to know this
The [winreg] module is required for the registry. Let's talk about the registry structure of Windows first.
>-----HKEY_CLASSES_ROOT >-----HKEY_CURRENT_USER registry >-----HKEY_LOCAL_MACHINE >-----HKEY_USERS >-----HKEY_CURRENT_CONFIG It can be roughly divided into: primary key--Subkey--Key value Functions used this time: winreg.ConnectRegistry(computer_name, key): Connect to the registry, computer_name=None Represents the local computer, otherwise use r"\\computername"Represents a remote computer, key Link for key. winreg.OpenKey(key, sub_key, reserved=0, access=KEY_READ): Open the specified key, key The key that has been opened, sub_key Key to open. winreg.QueryValueEx(key,value_name ): Retrieves the type and data of the specified value name associated with the registry key.
How to obtain interface information in Windows Environment:
#In Windows Environment import netifaces import pprint pp = pprint.PrettyPrinter(indent=4) pp.pprint(netifaces.interfaces()) #Return result: it is a list, all of which are a string of subkeys This corresponds to the network card one by one [ '{90788744-5655-4A9E-ADB6-A97CAE0F3B3F}', '{02685473-BCE5-4E19-AC64-0388FA81C13F}', '{5BBD6405-7C2E-4A78-8A09-31E03FAA3B75}', '{95FDA148-CA04-4926-87CD-FC0DC38FF89C}', '{D87FBBE0-11C0-49D1-A8CE-52DFC195B1B4}', '{E31B9D7C-6E73-4773-B564-1038BDB0EDAD}', '{A7584008-7824-4760-B2E0-1D0F483FD64E}', '{CD94297B-D746-4494-91F7-3E40C091A0FC}', #Spoiler, this is the only sub key of WLAN of wireless network card '{652C7833-4B8D-400F-A72F-F7C89C30FD03}', '{991AF727-67ED-11E9-B14B-806E6F6E6963}'] #Please remember that the key of my wireless network card WLAN is: {CD94297B-D746-4494-91F7-3E40C091A0FC} #How to get it will be introduced later; #Let's take a look at the information related to ipv4: pp.pprint(netifaces.ifaddresses('{CD94297B-D746-4494-91F7-3E40C091A0FC}')[netifaces.AF_INET] #Return results [ { 'addr': '172.20.18.37', 'broadcast': '172.20.18.255', 'netmask': '255.255.255.0'}] #Get ipv4 address pp.pprint(netifaces.ifaddresses('{CD94297B-D746-4494-91F7-3E40C091A0FC}')[netifaces.AF_INET][0]['addr']) '172.20.18.37' #Return results
3. Complete code
File 1: win_get_key.py
Description: run on windows system
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- #Welcome to WeChat official account: drip Technology from netifaces import interfaces import winreg as wr #Defines the function to obtain the registry key value of the network card interface of Windows system def get_key(ifname): #Get the key values of all network interface cards id = interfaces() #Dictionary for storing network card key value and key value name key_name = {} try: #Establish a linked registry, "HKEY_LOCAL_MACHINE", and None represents the local computer reg = wr.ConnectRegistry(None,wr.HKEY_LOCAL_MACHINE) # Open r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318} ', fixed reg_key = wr.OpenKey(reg , r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}') except : return ('Path error or other problems, please check carefully') for i in id: try: #Try to read the corresponding Name under the key value of each network card reg_subkey = wr.OpenKey(reg_key , i + r'\Connection') #If name exists, write key_name Dictionary key_name[wr.QueryValueEx(reg_subkey , 'Name')[0]] = i # print(wr.QueryValueEx(reg_subkey , 'Name')[0]) except FileNotFoundError: pass # print('List of all interface information Dictionaries: '+ str (key_name) +' \ n ') return key_name[ifname] if __name__ == '__main__': print(get_key('WLAN'))
File 2: python_netifaces.py
Note: it can be used on windows and Linux systems
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- #Welcome to WeChat official account: drip Technology from netifaces import ifaddresses ,AF_INET , AF_INET6 import platform #Define the function to get ipv4 information def get_ip_address(ifname): #Judge whether the system is Linux if platform.system() == "Linux": try: #Return ipv4 address information return ifaddresses(ifname)[AF_INET][0]['addr'] except ValueError: return None #Determine whether it is a Windows system elif platform.system() == "Windows": #Call function get_key, the key value of the network card is obtained from Tools.win_get_key import get_key key = get_key(ifname) if not key: return else: #Return ipv4 address information return ifaddresses(key)[AF_INET][0]['addr'] # Determine whether it is a Windows system elif platform.system() == 'MacOS': pass else: print('Your system does not support this program temporarily. At present, it only supports Linux,Windows,MacOS') #Define the function to obtain ipv6 information, which is roughly the same as the above functions, without remarks def get_ipv6_address(ifname): if platform.system() == "Linux": try: return ifaddresses(ifname)[AF_INET6][0]['addr'] except ValueError: return None elif platform.system() == "Windows": from Tools.win_get_key import get_key key = get_key(ifname) if not key: return else: return ifaddresses(key)[AF_INET6][0]['addr'] elif platform.system() == 'MacOS': pass else: print('Your system does not support this program temporarily. At present, it only supports Linux,Windows,MacOS') if __name__ == '__main__': print('Yours ipv4 the address is:' + get_ip_address('WLAN')) print('Yours ipv6 the address is:' + get_ipv6_address('WLAN')) #Results returned under Windows system: Yours ipv4 The address is: 192.168.100.203 Yours ipv6 The address is: 240 e:64:5222:2000:5d68:304d:6133:ab45
Results returned under Linux system:
...ellipsis... ...Code omission(ditto)... if __name__ == '__main__': #Switch to the remote Linux environment and modify as follows: print('Yours ipv4 the address is:' + get_ip_address('ens32')) print('Yours ipv6 the address is:' + get_ipv6_address('ens32')) #Results returned under Linux system Yours ipv4 The address is: 192.168.0.253 Yours ipv6 the address is: fe80::20c:29ff:fe5d:2f55%ens32
4. Broken words
This time is a little too long. I use the decomposition method to explain. I hope it will be useful to you, rather than posting the script.
In every article I write, I hope that for the network siege lion, how to use python to better improve work efficiency and operation and maintenance, not just limited to the traditional LAN and WAN. The technology is updated again, and personal skills and thinking need to adapt to the times and make common progress.
4.1 official reference link:
netifaces modular: https://pypi.org/project/netifaces/ winreg modular: https://docs.python.org/3/library/winreg.html#exception-changed
The above is the detailed content of python obtaining the network card information of the computer. For more information about python obtaining the network card information, please pay attention to other relevant articles of script home!