python输入实物码记录网卡IP及MAC地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import psutil
import pymysql
import datetime
import sys

def insent_db(adapter, mac, ipv4, swcode, sent_time):
try:
db = pymysql.connect(host="10.103.50.147", port=3306, user="crrcuser", password="abc.123456", database="gsdata",
charset="utf8")
cursor= db.cursor()
db.ping(reconnect=True)
new_list_1 = []
tup_1 = (adapter, mac, ipv4, swcode, sent_time)
new_list_1.append(tup_1)
sql = "insert into MAC_Collect(adapter, mac, ipv4, swcode, sent_time) values(%s, %s, %s, %s, %s)"
cursor.executemany(sql, new_list_1)
db.commit()# 提交数据库执行
cursor.close()
db.close()
return 0
except:
return sys.exc_info()

def PrintNetIfAddr():
""" 打印多网卡 mac 和 ip 信息 """
swcode = input("请输入实物码(实物码以SW开头):")
if swcode[:2] != "SW" and swcode[:2] != "sw":
print("实物码输入错误,请输入正确实物码(实物码以SW开头)!")
return 1
dic = psutil.net_if_addrs()
for adapter in dic:
snicList = dic[adapter]
mac = '无 mac 地址'
ipv4 = '无 ipv4 地址'
for snic in snicList:
if snic.family.name in {'AF_LINK', 'AF_PACKET'}:
mac = snic.address
elif snic.family.name == 'AF_INET':
ipv4 = snic.address
if mac == '无 mac 地址':
continue
if "蓝牙" in adapter:
continue
if ipv4[:2] != "10":
continue
sent_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
insent_db_str = insent_db(adapter, mac, ipv4, swcode, sent_time)
if insent_db_str:
return insent_db_str
else:
print("成功上传数据:",'%s, %s, %s, %s, %s' % (adapter, mac, ipv4, swcode, sent_time))
return 0
return "内网没有符合要求的MAC"
pro_end = PrintNetIfAddr()
if pro_end:
print(pro_end)
print("失败,按下任意键以退出程序")
else:
print("成功,按下任意键以退出程序")
input()