1 Star 0 Fork 0

Ragus/pycs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ip_mac_addr.py 2.75 KB
一键复制 编辑 原始数据 按行查看 历史
"""
实现的功能:
1. 局域网在线设备列表,hostname, ip addr, mac addr
2. 进一步,局域网内在线设备所开放的端口
3. 进一步,外网服务器地址开放端口扫描
以上功能,Linux下软件nmap可以解决。
如果使用Python的方式呢?
"""
# SO上给出的examples切实可用
# http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
import socket
# 返回本机hostname,alias,ip-lists
socket.gethostbyname_ex(socket.gethostname())
"""
使用系统指令实现:
1. ping -c1 DEST_IP_ADDR,目的主机是否可以ping通
2. arp -n DEST_IP_ADDR,arp查看 DEST_IP_ADDR 的mac地址
"""
from subprocess import Popen, PIPE
import re
IP = "192.168.10.111"
Popen(["ping", "-c 1", IP], stdout = PIPE)
pid = Popen(["arp", "-n", IP], stdout = PIPE)
s = pid.communicate()[0]
mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
print "%s--> %s" % (IP, mac)
"""
python-nmap模块:
python-nmap 0.6.1
python-nmap-0.6.1.tar.gz
This is a python class to use nmap and access scan results from python3
# 此模块使用系统nmap程序,返回包装其结果到python数据集中
# 如没有nmap就爱莫能助了。
# 模块地址:https://pypi.python.org/pypi/python-nmap
# 以下代码来自SO:https://askubuntu.com/questions/594660/how-can-i-get-the-mac-addresses-of-machines-using-python-nmap
"""
#!/usr/bin/env python
import nmap
nm = nmap.PortScanner()
cidr2='192.168.1.99/24'
a=nm.scan(hosts=cidr2, arguments='-sP')
for k,v in a['scan'].iteritems():
if str(v['status']['state']) == 'up':
print str(v)
try: print str(v['addresses']['ipv4']) + ' => ' + str(v['addresses']['mac'])
except: print str(v['addresses']['ipv4'])
"""
Windows下使用netsh,ipconfig,getmac指令获取系统不同网卡界面的mac地址
"""
from subprocess import Popen,PIPE
cmd = 'getmac -fo list -v' # 需要在terminal中运行的命令
rs = Popen(cmd,stdout=PIPE).communicate() # 获取stdout的字符串
print(rs)
# 一个大致的输出:
"""
(b'\r\n
Connection Name: lh\r\n
Network Adapter: Intel(R) 82577LM Gigabit Network Connection\r\n
Physical Address: F0-DE-F1-27-D4-0C\r\n
Transport Name: Media disconnected\r\n
\r\n
Connection Name: VMware Network Adapter VMnet1\r\n
Network Adapter: VMware Virtual Ethernet Adapter for VMnet1\r\n
Physical Address: 00-50-56-C0-00-01\r\n
Transport Name: \\Device\\Tcpip_{A4BC6FF4-4150-4D28-BB32-ADEC0B0D7EC3}\r\n
\r\n
Connection Name: VMware Network Adapter VMnet8\r\n
Network Adapter: VMware Virtual Ethernet Adapter for VMnet8\r\n
Physical Address: 00-50-56-C0-00-08\r\n
Transport Name: \\Device\\Tcpip_{C8F3E159-59A4-456B-A375-B080FEC23990}\r\n,
None)
"""
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/ragus/pycs.git
git@gitee.com:ragus/pycs.git
ragus
pycs
pycs
master

搜索帮助