"""
**声明:
# 扫描端口功能,get_ip_status()
# 获取网卡的Mac地址 ,network_card_mac()
# 局域网扫描器,scapy ,IP地址和MAC地址, scapy_network_ip_mac()
# 网段IP&Mac ARP协议扫描器,ip_mac_scanner()
# 获取网卡名称和其ip地址,get_netcard()**
"""
def get_ip_status(ip,port):
""" # 扫描指定IP 端口功能 """
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.connect((ip,port))
print('{0} port {1} is open'.format(ip, port))
except Exception as err:
print(err)
print('{0} port {1} is not open'.format(ip,port))
finally:
server.close()
host = '192.168.9.123'
for port in range(20,100):
get_ip_status(host,port)
def network_card_mac():
""" 获取网卡的Mac地址 """
from psutil import net_if_addrs
for k, v in net_if_addrs().items():
for item in v:
address = item[1]
if '-' in address and len(address) == 17:
print(address.replace("-", ":"))
def scapy_network_ip_mac():
""" 局域网扫描器,scapy ,IP地址和MAC地址 """
from scapy.layers.l2 import Ether, ARP
from scapy.sendrecv import srp
import socket
import re
try:
wind_host_name = socket.gethostname()
wind_ip = socket.gethostbyname(wind_host_name)
udp_gw_ip = str(re.findall(r'(?<!\d)\d{1,3}\.\d{1,3}\.\d{1,3}(?=\.\d)', wind_ip)[0]) + '.0'
wifi = '以太网'
if wifi:
p = Ether(dst='ff:ff:ff:ff:ff:ff') / ARP(pdst='%s/24' % udp_gw_ip)
ans, unans = srp(p, iface=wifi, timeout=5)
print("一共扫描到%d台主机:" % len(ans))
result = []
for s, r in ans:
result.append([r[ARP].psrc, r[ARP].hwsrc])
result.sort()
for ip, mac in result:
print(ip, '------>', mac)
except Exception as e:
print(e)
def ip_mac_scanner(hosts: str, local_mac: str, detail: bool = False):
"""
网段IP&Mac ARP协议扫描器
:param hosts: 网段 e.g.‘*.*.*.*/*’
:param local_mac: 本地MAC地址,e.g.‘**-**-**-**-**-**’
:param detail: 是否显示详细信息
:return: dict { IP: MAC, .... }
"""
from scapy.layers.l2 import Ether, ARP
from scapy.sendrecv import srp
import warnings
if detail:
print('scanning %s by ARP...' % hosts)
packet = Ether(dst="ff:ff:ff:ff:ff:ff", src=local_mac) / ARP(pdst=hosts)
if detail:
_Answer, _unAnswer = srp(packet, timeout=2, verbose=3)
else:
_Answer, _unAnswer = srp(packet, timeout=2, verbose=0)
if detail:
print("%d host(s) found:" % len(_Answer))
result = {}
for Send, Receive in _Answer:
_IP = Receive[ARP].psrc
_Mac = Receive[ARP].hwsrc
if _IP not in result:
result[_IP] = _Mac
else:
warnings.warn(
'{_IP_} -> {_nowMac_} unexpected. {_IP_} -> {_existMac_} is '
'already exist.'
.format(_IP_=_IP, _nowMac_=_Mac, _existMac_=result[_IP]))
if detail:
print(result)
return result
def get_netcard():
"""获取网卡名称和其ip地址 """
import psutil
netcard_info = []
info = psutil.net_if_addrs()
for k, v in info.items():
for item in v:
if item[0] == 2 and not item[1] == '127.0.0.1':
netcard_info.append((k, item[1]))
return netcard_info
if __name__ == '__main__':
pass
|