【Python】通过cmd的shell命令获取局域网内所有IP、MAC地址,通过主机名获取IP

【Python】通过cmd的shell命令获取局域网内所有IP、MAC地址,通过主机名获取IP

更新以gitee为准:
gitee

cmd命令获取IP

通过cmd命令可以查看出自身ip、网关下的所有设备等
所用的命令有:

ipconfig/allarp -a
在这里插入图片描述
其中 arp命令实际上是从网络缓存区去读取 如果重置了缓存区 则无法搜索到设备

故 可以通过ping命令将各个网关下的设备 然后再通过arp -a读取即可

代码层面上 可以通过多线程来加快ping的速度 同时也起到初步筛选作用

def ping_ip(ip):
    global current_ip_list
    try:
        result = subprocess.run(['ping', '-n','3',ip], 
                    capture_output=True, 
                    text=True,
                    creationflags=subprocess.CREATE_NO_WINDOW)
        if "TTL" in str(result.stdout):
            current_ip_list.append(ip)
    except:
        pass

同时 使用arp命令加强筛选

 result = subprocess.run(['arp', '-a'], 
                                capture_output=True, 
                                text=True,
                                creationflags=subprocess.CREATE_NO_WINDOW)                      

            self.device_list = []
            li = (str(result).split(current_ip+" ---")[1].split(":")[0]).split("\\n")
            for i in li:
                if ip in i:
                    match = re.search(r'(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F-]+)', i)
                    if match:                       
                        ip_addr, mac = match.groups()                               
                        for j in current_ip_list:
                            if j == ip_addr:                                
                                mac = mac.upper()
                                current_ip_list.remove(j)
                                self.device_list.append([ip_addr,mac,'',''])
                                break

代码逻辑即为 读取arp下的所有IP 然后筛选出正常通信的

ping主机名

通过ping命令可以获取主机名对应的IP 但是只能返回一个IP(通常是最近的一个)

代码实现如下:

result = subprocess.run(['ping', '-4','-n', '1', hostname],
                                    capture_output=True,
                                    text=True,
                                    creationflags=subprocess.CREATE_NO_WINDOW)

                # 匹配带方括号的IP地址
                ip_match = re.search(r'\[([\d.]+)\]', result.stdout)
                if ip_match:
                    ip = ip_match.group(1)
                    self.text_area.insert(tk.END, f"解析成功: {hostname} -> {ip}\n")
                    i=1
                else:
                    # 备用匹配模式
                    ip_match = re.search(r'\d+\.\d+\.\d+\.\d+', result.stdout)
                    if ip_match:
                        ip = ip_match.group()
                        self.text_area.insert(tk.END, f"解析成功: {hostname} -> {ip}\n")
                        i=1
                    else:
                        self.text_area.insert(tk.END, f"无法解析主机名: {hostname}\n")
                
                if i == 1:
                    # 在表格中查找IP
                    found = False
                    for item in self.tree.get_children():
                        if self.tree.item(item, 'values')[0] == ip:
                            # 标红匹配行
                            self.tree.tag_configure('found', background='#ff9999')
                            self.tree.item(item, tags=('found',))
                            self.tree.see(item)  # 滚动到该行
                            found = True
                            break
                    if not found:
                        # 插入新行(MAC设为未知)
                        new_item = self.tree.insert('', 'end', 
                                      values=(ip, "请重新扫描","",""),
                                      tags=('found',))
                        self.tree.tag_configure('found', background='#ff9999')
                        self.tree.see(new_item)  # 滚动到新条目

获取IP的主机名

通过nbtstat -A命令可以获取IP对应的主机名和工作组
对应代码:

def ping_name(num,current_ip):
    global current_ip_name
    ip = current_ip_name[num][0]
    
    name = ""
    group = ""

    r_list = []
    flag = 0

    try:
        result = subprocess.run(['nbtstat', '-A',ip], 
                    capture_output=True, 
                    text=True,
                    creationflags=subprocess.CREATE_NO_WINDOW)
        s = result.stdout
        if current_ip not in s:
            return
        s_list = s.split("\n")
        for i in s_list:
            if current_ip in i:
                flag = 1
            if flag:                
                if "0.0.0.0" in i:
                    break
                if "<" in i:
                    r_list.append(i.split("<")[0].replace(" ",""))
        if not r_list:
            return
        
        name = r_list[0]
        for i in r_list:
            if i == name:
                continue
            else:
                group = i
        if group == "":
            group = name
        current_ip_name[num][2] = name
        current_ip_name[num][3] = group
    except:
        pass

socket获取当前网关

在Python中可以直接通过socket获取当前所有网卡鄂网关及自身IP地址
代码为:

	def get_local_ip(self):
        try:
            ips = []
            # 获取所有网络接口的IP
            hostname = socket.gethostname()
            ip_list = socket.gethostbyname_ex(hostname)[2]
            
            # 新增UDP方式获取的活动接口IP
            with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
                s.connect(("8.8.8.8", 80))
                active_ip = s.getsockname()[0]
                if active_ip not in ip_list:
                    ip_list.append(active_ip)

            # 筛选私有地址并排序
            for ip in sorted(ip_list, key=lambda x: x != active_ip):
                if any([ip.startswith('192.168.'),
                       ip.startswith('10.'),
                       (ip.startswith('172.') and 15 < int(ip.split('.')[1]) < 32)]):
                    ips.append(ip)

            # 更新下拉框
            self.ip_combobox['values'] = ips
            if ips:
                self.ip_combobox.set(ips[0])
                self.update_gateway()
            else:
                self.ip_label.config(text="No valid IP found")

        except Exception as e:
            self.text_area.insert(tk.END, f"Network detection failed: {str(e)}\n")

运行效果

tkinter直接封装
在这里插入图片描述

附录:列表的赋值类型和py打包

列表赋值

BUG复现

闲来无事写了个小程序 代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

我在程序中 做了一个16次的for循环 把列表a的每个值后面依次加上"_"和循环序号
比如循环第x次 就是把第x位加上_x 这一位变成x_x 我在输出测试中 列表a的每一次输出也是对的
循环16次后列表a应该变成[‘0_0’, ‘1_1’, ‘2_2’, ‘3_3’, ‘4_4’, ‘5_5’, ‘6_6’, ‘7_7’, ‘8_8’, ‘9_9’, ‘10_10’, ‘11_11’, ‘12_12’, ‘13_13’, ‘14_14’, ‘15_15’] 这也是对的

同时 我将每一次循环时列表a的值 写入到空列表c中 比如第x次循环 就是把更改以后的列表a的值 写入到列表c的第x位
第0次循环后 c[0]的值应该是[‘0_0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘11’, ‘12’, ‘13’, ‘14’, ‘15’] 这也是对的
但是在第1次循环以后 c[0]的值就一直在变 变成了c[x]的值
相当于把c_list[0]变成了c_list[1]…以此类推 最后得出的列表c的值也是每一项完全一样
我不明白这是怎么回事
我的c[0]只在第0次循环时被赋值了 但是后面它的值跟着在改变

如图:
在这里插入图片描述
第一次老出bug 赋值以后 每次循环都改变c[0]的值 搞了半天都没搞出来
无论是用appen函数添加 还是用二维数组定义 或者增加第三个空数组来过渡 都无法解决

代码改进

后来在我华科同学的指导下 突然想到赋值可以赋的是个地址 地址里面的值一直变化 导致赋值也一直变化 于是用第二张图的循环套循环深度复制实现了

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        for i in range(16):
            c_list[j].append(a_list[i])
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
print(c_list,'\n')    

解决了问题

在这里插入图片描述

优化

第三次是请教了老师 用copy函数来赋真值

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list.copy()
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

同样能解决问题
在这里插入图片描述
最后得出问题 就是指针惹的祸!

a_list指向的是个地址 而不是值 a_list[i]指向的才是单个的值 copy()函数也是复制值而不是地址

如果这个用C语言来写 就直观一些了 难怪C语言是基础 光学Python不学C 遇到这样的问题就解决不了

C语言yyds Python是什么垃圾弱智语言

总结

由于Python无法单独定义一个值为指针或者独立的值 所以只能用列表来传送
只要赋值是指向一个列表整体的 那么就是指向的一个指针内存地址 解决方法只有一个 那就是将每个值深度复制赋值(子列表内的元素提取出来重新依次连接) 或者用copy函数单独赋值

如图测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
部分代码:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 16:45:48 2021

@author: 16016
"""

def text1():
    A=[1,2,3]
    B=[[],[],[]]
    for i in range(len(A)):
        A[i]=A[i]+i
        B[i]=A
        print(B)

def text2():
    A=[1,2,3]
    B=[[],[],[]]
    
    A[0]=A[0]+0
    B[0]=A
    print(B)
    A[1]=A[1]+1
    B[1]=A
    print(B)
    A[2]=A[2]+2
    B[2]=A
    print(B)
    
if __name__ == '__main__':
    text1()
    print('\n')
    text2()

py打包

Pyinstaller打包exe(包括打包资源文件 绝不出错版)

依赖包及其对应的版本号

PyQt5 5.10.1
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.0

pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3

Pyinstaller -F setup.py 打包exe

Pyinstaller -F -w setup.py 不带控制台的打包

Pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包

打包exe参数说明:

-F:打包后只生成单个exe格式文件;

-D:默认选项,创建一个目录,包含exe文件以及大量依赖文件;

-c:默认选项,使用控制台(就是类似cmd的黑框);

-w:不使用控制台;

-p:添加搜索路径,让其找到对应的库;

-i:改变生成程序的icon图标。

如果要打包资源文件
则需要对代码中的路径进行转换处理
另外要注意的是 如果要打包资源文件 则py程序里面的路径要从./xxx/yy换成xxx/yy 并且进行路径转换
但如果不打包资源文件的话 最好路径还是用作./xxx/yy 并且不进行路径转换

def get_resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

而后再spec文件中的datas部分加入目录
如:

a = Analysis(['cxk.py'],
             pathex=['D:\\Python Test\\cxk'],
             binaries=[],
             datas=[('root','root')],
             hiddenimports=[],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

而后直接Pyinstaller -F setup.spec即可

如果打包的文件过大则更改spec文件中的excludes 把不需要的库写进去(但是已经在环境中安装了的)就行

这些不要了的库在上一次编译时的shell里面输出
比如:
在这里插入图片描述

在这里插入图片描述
然后用pyinstaller --clean -F 某某.spec

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嵌入式拳铁编曲MikeZhou

光电帝国,光联万物!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值