查询设备的IP地址/掩码/MAC/网关

时间:2022-06-13 06:33:13
import commands, sys
import platform
from _utils.patrol2 import run_cmd, data_format, report_format
from psutil import net_if_addrs
import os
import uuid def get_net_info():
sysstr = platform.system()
if (sysstr == "Windows"):
results = []
code, gateway = run_cmd("chcp 437| ipconfig /all")
print gateway
if code:
return data_format('网卡IP/掩码/MAC地址/网关', '数据获取异常', 1)
else:
flag = 0
for i in gateway.split(os.linesep):
if flag == 1 and (':' not in i or '.' not in i.split(':')[0]) and i:
results.append(i.strip())
else:
flag = 0
if 'Default Gateway' in i:
flag = 1
if flag == 1 and i:
results.append(i)
result = []
for i in results:
if '.' in i.split(':')[1]:
result.append(i.split(':')[1].strip())
gateway=','.join(result) address = hex(uuid.getnode())[2:]
mac_host = '-'.join(address[i:i + 2] for i in range(0, len(address), 2)) code, ipnets = run_cmd('chcp 437| ipconfig /all')
if code:
return data_format('网卡IP/掩码/MAC地址/网关', ipnets, 1)
else:
ipnets = ipnets.split('\n') result = []
ips = []
for k, v in net_if_addrs().items():
mac = ''
ip = ''
mask = ''
for item in v:
if item.family == -1:
mac = item.address
elif item.family == 2:
ip = item.address
mask = item.netmask if not mac:
mac = mac_host
if ip and ip != '127.0.0.1' and ip not in ips:
flag=0
for i in ipnets:
if 'IPv4' in i.split(':')[0]:
flag=1
if flag==1 and ('子网掩码' in i or 'Subnet Mask' in i):
flag=0
mask=i.split(':')[1].strip() ips.append(ip)
result.append('{}/{}/{}/{}'.format(ip, mask, mac,gateway))
report = data_format('网卡IP/掩码/MAC地址/网关', '\n\n'.join(result), 0)
else:
address = hex(uuid.getnode())[2:]
mac_host = '-'.join(address[i:i + 2] for i in range(0, len(address), 2)) if os.uname()[0] != 'Linux':
code, ipnets = run_cmd('Lang=C;ifconfig -a')
if code:
return data_format('网卡IP/掩码/MAC地址/网关', ipnets, 1)
else:
ipnets = ipnets.split('\n')
code, gateway = run_cmd("Lang=C;netstat -rn|grep default| awk '{ print $2}'")
if code:
return data_format('网卡IP/掩码/MAC地址/网关', gateway, 1)
else:
code, gateway = run_cmd("Lang=C;ip route show | grep '^default' | awk '{ print $3}'")
if code:
return data_format('网卡IP/掩码/MAC地址/网关', gateway, 1) result = []
ips = []
for k, v in net_if_addrs().items():
mac = ''
ip = ''
mask = ''
for item in v:
if item.family == -1:
mac = item.address
elif item.family == 2:
ip = item.address
mask = item.netmask if not mac:
mac = mac_host
if ip != '127.0.0.1' and ip not in ips:
if os.uname()[0] != 'Linux':
for i in ipnets:
if ip in i:
mask = i.split('netmask')[1].split()[0].strip()
c = str(bin(int(mask, 16))[2:])
mask = '{}.{}.{}.{}'.format(int(c[0:8], 2), int(c[9:17], 2),
int(c[18:26], 2), int(c[27:35], 2)) ips.append(ip)
result.append('{}/{}/{}/{}'.format(ip, mask, mac,gateway))
report = data_format('网卡IP/掩码/MAC地址/网关', '\n\n'.join(result), 0)
return report reports = report_format(platform.node(), [get_net_info()], is_json=True)