获取本机网络信息

此代码获取一下信息:

网卡名称(NicName)

IP地址(IPAddr)

子网掩码(IPNetmask)

网关地址(Gateway)

外网出口地址(outsideIp)

需要用pip3安装 netifaces、requests、re三个外部模块

需要连接外部URL“http://2019.ip138.com/ic.asp

代码如下:

 

#!/usr/bin/python3

import netifaces

import requests

import re

import os

import socket

 

HostName = socket.gethostname()

UserName = os.getlogin()

 

url = "http://2019.ip138.com/ic.asp"

html = requests.get(url).text

str1 = str(re.findall(r'[0-9]+(?:\.[0-9]+){3}',html))

outsideIp = str1[2:-2]

 

Gateway = netifaces.gateways()['default'][netifaces.AF_INET][0]

NicName = netifaces.gateways()['default'][netifaces.AF_INET][1]

 

for interface in netifaces.interfaces():

if interface == NicName:

NicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]['addr']

IPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['addr']

IPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]['netmask']

 

 

print("Host Name is:", HostName)

print("User Name is:", UserName)

print("NIC Name is:", NicName)

print("IP Address is:", IPAddr)

print("Mask of IP is:", IPNetmask)

print("Mac address is:", NicMacAddr)

print("Gateway is:", Gateway)

print("outside IP is:", outsideIp)

 

输出结果:

[root@im-manage-1 py-code]# python3 get_net_info.py 
Host Name is: im-manage-1
User Name is: zp
NIC Name is: ens192
IP Address is: 10.11.10.81
Mask of IP is: 255.255.255.0
Mac address is: 00:50:56:9e:04:46
Gateway is: 10.11.10.1
outside IP is: 120.133.128.74
[root@im-manage-1 py-code]#

 
posted @ 2019-07-09 14:50  gujob  阅读(404)  评论(0编辑  收藏  举报