0. Preface
Under normal circumstances, if you want to see the computer's network card IP address or MAC address, directly through the interface to find the network card to view it, or through commands such as linux ifconfig to get the IP and other information, then this section teaches you how to get the network card through the python way to get the IP/MAC information.
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 of tools:
pycharm Professional Edition note:Professional Edition支持本地远程linuxadjust components during testing。
2. Module presentations and demonstrations
This time, only 3 modules are needed to get it done, but it's quite a lot of work.
- netifaces //need to be installed, mainly used to get the network card interface IP/MAC and other information;
- winreg //Built-in module, mainly used for Windows system to get the NIC interface key value through the registry;
- platform //Built-in module, mainly used to determine the system type: such as Widows, Linux, MacOS, etc.;
2.1 Example of using the platform module
Linux.
import platform () 'Linux' #Return results
Windows:
import platform () 'Windows' #Return results
2.2 Example of netifaces module usage
External module, please refer to the internet for the installation method, ignore it here (it's very simple).
Usage: Used to collect information such as network interface (IP/address/gateway).
The netiface module is ordered with 3 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
Let's look at the address family first:
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- # Welcome to follow the public number of WeChat: point drop technology # The following demonstration in a Linux environment from netifaces import pprint pp = (indent=4) # It's more intuitive to use print output here (netifaces.address_families) # Return results: { 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 for #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 all focus on: AF_NET, AF_NET6 #The rest of you can do your own research
2.2.1 How to get information about network card ports in Linux environment
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- # Welcome to WeChat: DotDropTechnology import netifaces import pprint pp = (indent=4) () ['lo', 'ens32'] # Return result, ubuntu system NIC ID (('ens32')) # Returns the result, which is a dictionary with nested lists, so be careful when slicing the { 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'}]} ('ens32')[netifaces.AF_INET][0]['addr'] '192.168.0.253' # Returns the result and gets the IPv4 address ('ens32')[netifaces.AF_PACKET][0]['addr'] '00:0c:29:5d:2f:55' # Return the result, get the MAC address of IPv4 ('ens32')[netifaces.AF_INET6][0]['addr'] 'fe80::20c:29ff:fe5d:2f55%ens32' #Return results,getIPv6address
2.2.2 How to get the information of NIC port in Windows environment
Note: windows value compared to Linux is much more complex, not directly based on the interface to obtain ip information, you need to find a unique string of keys, and then you can rely on it to get to the interface ip information, here I first give an example, so that we do not have to look at the confusion:
My wireless card information:
Wireless card name: WLAN
Corresponding key on the registry: {CD94297B-D746-4494-91F7-3E40C091A0FC} //python needs to know about this one
Registry needs to use the [winreg] module, let's talk about the Windows registry structure first briefly.
>-----HKEY_CLASSES_ROOT >-----HKEY_CURRENT_USER registration form >-----HKEY_LOCAL_MACHINE >-----HKEY_USERS >-----HKEY_CURRENT_CONFIG divide sth. into general terms:primary key--subkey--key value Functions used this time: (computer_name, key): 连接registration form,computer_name=NoneIndicates a local computer,or else user"\\computername"Indicates a remote computer,keyLinks for keys。 (key, sub_key, reserved=0, access=KEY_READ): Open the specified key,keyOpened keys,sub_keyKey to open。 (key,value_name ): 检索registration form项关联的指定值名称的类型和数据。
How to get interface information in Windows environment:
# The following in a Windows environment import netifaces import pprint pp = (indent=4) (()) #Return result: it's a list, it's all a bunch of subkeys... This one. - It's from the corresponding network card. [ '{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 alert, this is the only subkey for the wireless card WLAN '{652C7833-4B8D-400F-A72F-F7C89C30FD03}', '{991AF727-67ED-11E9-B14B-806E6F6E6963}'] # Please remember first that my wireless card WLAN key is: {CD94297B-D746-4494-91F7-3E40C091A0FC} # How to get it will be described later; # First look at getting ipv4 related information: (('{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 (('{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 to use
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- # Welcome to WeChat: DotDropTechnology from netifaces import interfaces import winreg as wr # Define a function to get the registry key of the Windows NIC interface. def get_key(ifname): # Get keys for all network interface cards id = interfaces() # Dictionary holding NIC key values and key names key_name = {} try: # Create linked registry, "HKEY_LOCAL_MACHINE", None for local computer reg = (None,wr.HKEY_LOCAL_MACHINE) # Open r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}', the fixed reg_key = (reg , r'SYSTEM\CurrentControlSet\Control\Network\{4d36e972-e325-11ce-bfc1-08002be10318}') except : return ('Path error or other problem, please double check') for i in id: try: # Try to read the corresponding Name under each NIC key value reg_subkey = (reg_key , i + r'\Connection') # If Name exists, write to key_name dictionary key_name[(reg_subkey , 'Name')[0]] = i # print((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
Description: Runs on Window and Linux systems using the
#!/usr/bin/env python3 #-*- coding:UTF-8 -*- # Welcome to WeChat: DotDropTechnology from netifaces import ifaddresses ,AF_INET , AF_INET6 import platform #Define functions to get ipv4 information def get_ip_address(ifname): # Determine if the system is Linux if () == "Linux": try: # Return ipv4 address information return ifaddresses(ifname)[AF_INET][0]['addr'] except ValueError: return None # Determine if it is a Windows system elif () == "Windows": # Call the function get_key to get the key value of the NIC 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 if it's Windows elif () == 'MacOS': pass else: print('Your system is not supported by this program at the moment, only Linux, Windows, MacOS are currently supported') # Define a function to get ipv6 information, much the same as the above function, no remarks def get_ipv6_address(ifname): if () == "Linux": try: return ifaddresses(ifname)[AF_INET6][0]['addr'] except ValueError: return None elif () == "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 () == 'MacOS': pass else: print('Your system is not supported by this program at the moment, only Linux, Windows, MacOS are currently supported') if __name__ == '__main__': print('Your ipv4 address is:' + get_ip_address('WLAN')) print('Your ipv6 address is:' + get_ipv6_address('WLAN')) # Results returned under Windows: yoursipv4The address is:192.168.100.203 yoursipv6The address is:240e:64:5222:2000:5d68:304d:6133:ab45
Returns results under Linux:
...an omission... ...代码an omission(ibid)... if __name__ == '__main__': # Switch to a remote Linux environment and make the following changes: print('Your ipv4 address is:' + get_ip_address('ens32')) print('Your ipv6 address is:' + get_ipv6_address('ens32')) #Results returned under Linux yoursipv4The address is:192.168.0.253 yoursipv6The address is:fe80::20c:29ff:fe5d:2f55%ens32
4. Shattered words
It's a bit lengthy this time around, so I'm using a break down to explain it, so I hope it's useful, rather than a handful of scripts to post up.
Every article I write, I hope that for the network attack lion, can how to use python to better improve the efficiency of work and operation and maintenance, and not just limited to the traditional LAN, WAN, etc., technology and then iterative update, personal skills thinking more need to adapt to the times, and progress together.
4.1 Official Reference Links:
netifacesmodule (in software): /project/netifaces/ winregmodule (in software): /3/library/#exception-changed
The above is python to get the computer's network card information in detail, more information about python to get the network card information please pay attention to my other related articles!