首页 > 编程语言 >Python获取当前在线设备ip和mac地址

Python获取当前在线设备ip和mac地址

时间:2022-11-24 22:58:51浏览次数:37  
标签:Python ip 192.168 df mac res line segment net

获取局域网所在的网段

with os.popen("ipconfig /all") as res:
    for line in res:
        line = line.strip()
        if line.startswith("IPv4"):
            ipv4 = map(int, re.findall("(\d+)\.(\d+)\.(\d+)\.(\d+)", line)[0])
        elif line.startswith("子网掩码"):
            mask = map(int, re.findall("(\d+)\.(\d+)\.(\d+)\.(\d+)", line)[0])
            break
net_segment = ".".join([str(i & j) for i, j in zip(ipv4, mask)]).strip(".0")
net_segment

结果:

'192.168.3'

当前我们实际只会使用最后一个位置作为网段,并不需要考虑子网掩码,所以可以简化代码:

with os.popen("ipconfig /all") as res:
    for line in res:
        line = line.strip()
        if line.startswith("IPv4"):
            net_segment = re.findall("(\d+\.\d+\.\d+)\.\d+", line)[0]
            break
net_segment

完整代码:

import os
import re
import time
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED

import pandas as pd


def get_net_segment():
    with os.popen("arp -a") as res:
        for line in res:
            line = line.strip()
            if line.startswith("接口"):
                net_segment = re.findall(
                    "(\d+\.\d+\.\d+)\.\d+", line)[0]
                break
    return net_segment


def ping_net_segment_all(net_segment):
    # for i in range(1, 255):
    #     os.system(f"ping -w 1 -n 1 {net_segment}.{i}")
    with ThreadPoolExecutor(max_workers=4) as executor:
        for i in range(1, 255):
            executor.submit(os.popen, f"ping -w 1 -n 1 {net_segment}.{i}")


def get_arp_ip_mac():
    header = None
    with os.popen("arp -a") as res:
        for line in res:
            line = line.strip()
            if not line or line.startswith("接口"):
                continue
            if header is None:
                header = re.split(" {2,}", line.strip())
                break
        df = pd.read_csv(res, sep=" {2,}",
                         names=header, header=0, engine='python')
    return df


def ping_ip_list(ips, max_workers=4):
    print("正在扫描在线列表")
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_tasks = []
        for ip in ips:
            future_tasks.append(executor.submit(os.popen, f"ping -w 1 -n 1 {ip}"))
        wait(future_tasks, return_when=ALL_COMPLETED)


if __name__ == '__main__':
    # 是否进行初始扫描
    init_search = False
    if init_search:
        print("正在扫描当前网段所有ip,预计耗时1分钟....")
        ping_net_segment_all(get_net_segment())

    last = None
    while 1:
        df = get_arp_ip_mac()
        df = df.loc[df.类型 == "动态", ["Internet 地址", "物理地址"]]
        if last is None:
            print("当前在线的设备:")
            print(df)
        else:
            online = df.loc[~df.物理地址.isin(last.物理地址)]
            if online.shape[0] > 0:
                print("新上线设备:")
                print(online)
            offline = last[~last.物理地址.isin(df.物理地址)]
            if offline.shape[0] > 0:
                print("刚下线设备:")
                print(offline)
        time.sleep(5)
        ping_ip_list(df["Internet 地址"].values)
        last = df

结果如下:

当前在线的设备:
     Internet 地址               物理地址
0    192.168.3.3  3c-7c-3f-83-e2-7c
1   192.168.3.10  3c-7c-3f-80-08-1b
2   192.168.3.25  f0-2f-74-82-15-7e
3   192.168.3.26  f0-2f-74-82-15-a2
4   192.168.3.28  f0-2f-74-82-15-38
5   192.168.3.29  f0-2f-74-82-15-d0
6   192.168.3.32  f0-2f-74-82-15-3b
7   192.168.3.33  f0-2f-74-82-15-56
8   192.168.3.39  a8-5e-45-16-79-99
9  192.168.3.225  30-24-a9-5a-eb-82
新上线设备:
    Internet 地址               物理地址
9  192.168.3.52  3c-7c-3f-c2-cd-cb
刚下线设备:
    Internet 地址               物理地址
9  192.168.3.52  3c-7c-3f-c2-cd-cb

大功告成了...

标签:Python,ip,192.168,df,mac,res,line,segment,net
From: https://www.cnblogs.com/michael999/p/16923730.html

相关文章

  • 学习python-Day92
    requests高级用法https和http的区别https=http+ssl或者tsl(ssl或tsl是加密的证书)注意:没有认证的机构就是没有签发证书,访问的时候,浏览器会提示不安全的。ssl认证......
  • effective python
    第8条用zip函数同时遍历两个迭代器内置的zip函数可以同时遍历多个迭代器。zip会创建惰性生成器,让它每次只生成一个元组,所以无论输入的数据有多长,它都是一个一个处理的......
  • TypeScript类型(二)
    对象 示例://#regionjs写法//object表示一个js对象leta:object;a={};a=function(){};//#endregion//#regionTypeScript写法//{}用来指定对......
  • Python爬虫学习-cnblog
    Python爬虫学习Python的文件操作序列化与反序列化通过文件操作,我们可以将字符串写入到一个本地文件。但是如果是一个对象(列表、字典、元组等),就无法直接写入到一个文件中......
  • Python实验报告(第12章)
      实验12:GUI界面编程一、实验目的和要求1、学会应用常用控件;2、学会使用BoxSizer布局;3、学会事件处理。二、实验环境软件版本:Python3.1064_bit三、实验过程......
  • TypeScript类型声明
    基本类型类型声明类型声明是TS非常重要的一个特点通过类型声明可以指定TS中变量(参数、形参)的类型指定类型后,当为变量赋值时,TS编译器会自动检查值是否符合类型......
  • 2022NOIP A层联测34 bs 串 英语作文 计算器 愤怒的小鸟
    T1[图论:并查集维护寻找特殊环]给出一个无向图,点权是0或者1,你可以从任意起点出发,每到达一个点,把这个点的权值放到你构造的字符串的末尾,并且这个点的权值取反。给出K次操作,......
  • iptables实现SNAT和DNAT,并对规则持久保存
    iptables实现SNAT和DNAT,并对规则持久保存#环境检查[root@PC-1~]#hostname-I192.168.100.11[root@PC-2~]#hostname-I192.168.100.12eth1:192.168.100.13[r......
  • Public NOIP Round #4(Div. 1) 题解
    T1:容易发现每种药品之间互不影响,对每种药品分别计算,对于它所涉及到的区间开个vector存下来,离散化之后差分,然后前缀和,数出只有它一个线段覆盖的段即可。时间复杂度\(\m......
  • 【解决】python获取文件大小,下载进度条报错KeyError: 'content-length'
    python3使用requesthttpx下载文件,获取不到文件大小,response没有content-lengthheader最简单的排查问题的办法就是用浏览器去下载如果浏览器在下载时,也不显示总大小,那......