Python获取当前在线设备ip和mac地址
获取局域网所在的网段
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和mac地址的更多相关文章
- 使用ARP获取局域网内设备IP和MAC地址
根据Arp列表数据,查询本地设备在线状态 使用 arp -a 获得所有内网地址,首先看Mod对象 public struct MacIpPair { public string HostName; p ...
- 获取客户机的ip和mac地址
只获取clientIP package com.ppms.utils; import javax.servlet.http.HttpServletRequest; /** * Created by l ...
- Java获取本机的IP与MAC地址
有些机器有许多虚拟的网卡,获取IP地址时会出现一些意外,所以需要一些验证: // 获取mac地址 public static String getMacAddress() { try { Enumer ...
- C#获取路由器外网IP,MAC地址
C#实现的获取路由器MAC地址,路由器外网地址.对于要获取路由器MAC地址,一定需要知道路由器web管理系统的用户名和密码.至于获取路由器的外网IP地址,可以不需要知道路由器web管理系统的用户名和密 ...
- JAVA获取本机IP和Mac地址
在项目中,时常需要获取本机的Ip或是Mac地址,进行身份和权限验证,本文就是通过java代码获取ip和Mac. package com.svse.query;import java.net.In ...
- 使用Python获取计算机名,ip地址,mac地址等等
获取计算机名 # 获取计算机名,常用的方法有三种 import os import socket # method one name = socket.gethostname() print(name ...
- 获取本机IP、mac地址、计算机名
python获取本机IP.mac地址.计算机名 在python中获取ip地址和在php中有很大不同,我们先来看一下python 获得本机MAC地址: >>> import uuid ...
- 获取Android设备WIFI的MAC地址 “MAC地址”
需要指出的是:wifi状态和wifi AP状态是互斥的状态:也就是一旦发现WIFI AP打开,WIFI是不能被打开的. 获取Android设备的WIFI MAC地址,首先需要将设备中的WIFI个人热点 ...
- 获取平台所有接口的IP和MAC地址
我们有时候会有获取网口的IP和MAC地址的需求.可以通过ioctl来获取. #include <sys/ioctl.h>#include <net/if.h>#include ...
- java获取本机名称、IP、MAC地址和网卡名称
java获取本机名称.IP.MAC地址和网卡名称 摘自:https://blog.csdn.net/Dai_Haijiao/article/details/80364370 2018年05月18日 1 ...
随机推荐
- oralce 语句指定的转换无效
公司的小师妹出现了个问题 让我帮忙看一下 在plsql 中查询语句没问题, 但是放到程序中会提示指定的转换无效 是因为存在无限小数 加上round(JJYHL,2) JJYHL就可以了
- URLSearchParams(鲜为人知处理URL地址的技能)
最近学习中无意发现url新处理方式,看到之后十分感兴趣就整理了一下. URLSearchParams URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串.参照 URL ...
- kubeSphere v3.3.0+kubernetes v1.22.10 集群部署
概述 KubeSphere 是 GitHub 上的一个开源项目,是成千上万名社区用户的聚集地.很多用户都在使用 KubeSphere 运行工作负载.对于在 Linux 上的安装,KubeSphere ...
- winform 中 label透明化
label1.BackColor = Color.Transparent;//设置背景颜色为透明 label1.Parent = pictureBox1;//将pictureBox1设为标签的父控件, ...
- react 二级路由嵌套
嵌套路由之后,静态文静路径错误, 更改webpack 打包output 输出根目录,publicPath:'/',二级路由刷新之后白屏,在首页模板文件中路径前加 /,
- locust 检查点、集合点、参数化设置。
1.参数化 方式1:循环取数据,数据可以重复使用. 所有并发虚拟用户共享同一份测试数据,各虚拟用户在数据列表中循环取值. 例如,模拟10个用户并发请求网页,总共有4个URL地址,每个虚拟用户都会依次循 ...
- Java笔记_递归回溯之小老鼠出迷宫问题
递归回溯之小老鼠出迷宫问题 直接看代码 /** * @ClassName MiGong01 * @Description TODO * @Author Orange * @Date 2021/4/16 ...
- sql执行多条语句
问题背景: 今天想在xml里面写一个sql,执行批量修改, update question_rules set score=${rule.score}, data_describe=#{rule.da ...
- react native 布局问题
1. Text组件里面的 文字垂直居中 <Text style={styles.confirmButtonStyle}>确认</Text> confirmButtonStyle ...
- fetch,axios简介与语法
fetch简介&语法 留心:像之前的XMLHttpRequest 但并不真的是,而是代替的 #概念:fetch是ecma组织基于promise开发http api ,用来代替xhr #语法: ...