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 ...
随机推荐
- kail 系统更新
原文链接:https://blog.csdn.net/aiming66/article/details/123203495
- unity 实现Game窗口的Stats 【转自蛮牛】
using UnityEngine;using System.Text;using UnityEditor; public class ShowFps : MonoBehaviour{ public ...
- Mac下MySQL下载及安装
1在浏览器当中输入地址: https://downloads.mysql.com/archives/community/ 1. 1.1,选择mysql版本,它会自动对应某个版本macOS,1.2 ...
- maven-阿里云镜像
<mirror> <id>nexus-aliyun</id> <mirrorOf>*,!jeecg,!jeecg-snapshots&l ...
- java学习一:java介绍及第一个helloword程序
1.java语言介绍 java是一门后台开发语言 大型web语言系统开发,app后台服务首选开发语言 java这门语言大特点:跨平台,安全性高,有丰富的类库 核心思想:面向对象 2.Jdk介绍 3.为 ...
- [746] Interlude Update 3
[746] Interlude Update 3 Client 00 SendProtocolVersion 01 MoveBackwardToLocation 02 Say 03 RequestEn ...
- pytorch的三种量化方式详解
pytorch的三种量化方式详解 这篇博客详细介绍了pytorch官方教程提到的三种量化方式的原理,详细解释了三种量化方式的区别: 1. 静态量化 :torch.quantize_per_tensor ...
- 代码格式 linux
indent -kr -i8 -ts8 -sob -l80 -ss -bs -psl test.c
- pycharm 连接 docker容器
1.ubuntu 18.04 先安装sudo apt-get install openssh-server 2.修改" /etc/ssh/sshd_config" 改成 Permi ...
- ROS2
ROS2核心概念 节点 创建节点流程 编程接口初始化 创建节点并初始化 实现节点功能 销毁节点并关闭接口 #!/usr/bin/env python3 import rclpy # ROS2 Pyth ...