怎么用脚本获取网络设备列表

wen 实用脚本 3

本文目录导读:

怎么用脚本获取网络设备列表

  1. Python + Scapy (ARP扫描)
  2. Python + Netmiko (网络设备管理)
  3. Bash + arp-scan/nmap
  4. Python + SNMP
  5. Windows PowerShell
  6. 综合管理脚本 (Python)
  7. 使用建议

Python + Scapy (ARP扫描)

#!/usr/bin/env python3
from scapy.all import ARP, Ether, srp
import socket
import ipaddress
def get_network_devices(network="192.168.1.0/24"):
    # 创建ARP请求包
    arp = ARP(pdst=network)
    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    packet = ether/arp
    # 发送并接收响应
    result = srp(packet, timeout=3, verbose=0)[0]
    devices = []
    for sent, received in result:
        devices.append({
            'ip': received.psrc,
            'mac': received.hwsrc
        })
    return devices
# 使用示例
if __name__ == "__main__":
    devices = get_network_devices("192.168.1.0/24")
    print("活跃设备列表:")
    print("IP地址\t\tMAC地址")
    for device in devices:
        print(f"{device['ip']}\t{device['mac']}")

Python + Netmiko (网络设备管理)

#!/usr/bin/env python3
from netmiko import ConnectHandler
import json
def get_device_inventory():
    # 设备列表配置
    devices = [
        {
            'device_type': 'cisco_ios',
            'host': '192.168.1.1',
            'username': 'admin',
            'password': 'password',
        },
        {
            'device_type': 'huawei',
            'host': '192.168.1.2',
            'username': 'admin',
            'password': 'password',
        }
    ]
    inventory = []
    for device in devices:
        try:
            connection = ConnectHandler(**device)
            # 获取设备信息
            hostname = connection.send_command('show hostname')
            interfaces = connection.send_command('show ip interface brief')
            version = connection.send_command('show version')
            inventory.append({
                'host': device['host'],
                'hostname': hostname,
                'interfaces': interfaces,
                'version': version.split('\n')[0]
            })
            connection.disconnect()
        except Exception as e:
            print(f"连接设备 {device['host']} 失败: {e}")
    return inventory

Bash + arp-scan/nmap

#!/bin/bash
# 使用 arp-scan
echo "=== 方法1: arp-scan ==="
sudo arp-scan --localnet --interface eth0
# 使用 nmap
echo -e "\n=== 方法2: nmap ==="
nmap -sn 192.168.1.0/24

Python + SNMP

#!/usr/bin/env python3
from pysnmp.hlapi import *
import threading
def get_arp_table(ip="192.168.1.1", community="public"):
    """通过SNMP获取ARP表"""
    arp_table = []
    # OID for IP-MIB::ipNetToMediaPhysAddress
    oid = ObjectIdentity('1.3.6.1.2.1.4.22.1.2')
    iterator = getCmd(
        SnmpEngine(),
        CommunityData(community),
        UdpTransportTarget((ip, 161)),
        ContextData(),
        ObjectType(oid),
        lexicographicMode=False
    )
    for errorIndication, errorStatus, errorIndex, varBinds in iterator:
        if errorIndication or errorStatus:
            break
        for varBind in varBinds:
            arp_table.append(str(varBind[1]))
    return arp_table

Windows PowerShell

# 获取ARP表
Get-NetNeighbor -AddressFamily IPv4
# 获取活动网络连接
Get-NetTCPConnection -State Established | Select LocalAddress, LocalPort, RemoteAddress, RemotePort
# 获取网卡信息
Get-NetAdapter | Select Name, InterfaceDescription, MacAddress
# 扫描局域网设备
1..254 | ForEach-Object {
    $ip = "192.168.1.$_"
    $result = Test-Connection -ComputerName $ip -Count 1 -Quiet
    if ($result) {
        Write-Host "$ip 在线" -ForegroundColor Green
    }
}

综合管理脚本 (Python)

#!/usr/bin/env python3
import subprocess
import json
import socket
from concurrent.futures import ThreadPoolExecutor
class NetworkScanner:
    def __init__(self, subnet="192.168.1.0/24"):
        self.subnet = subnet
        self.devices = []
    def arp_scan(self):
        """使用arp-scan扫描"""
        cmd = f"sudo arp-scan --localnet --interface eth0 --json"
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        try:
            data = json.loads(result.stdout)
            return data
        except:
            return []
    def ping_scan(self, ip):
        """Ping扫描单个IP"""
        try:
            subprocess.run(['ping', '-c', '1', '-W', '1', ip], 
                          capture_output=True, timeout=2)
            return ip
        except:
            return None
    def ping_sweep(self):
        """全网段Ping扫描"""
        network = ipaddress.ip_network(self.subnet)
        ips = [str(ip) for ip in network.hosts()]
        with ThreadPoolExecutor(max_workers=50) as executor:
            results = executor.map(self.ping_scan, ips)
            active_ips = [ip for ip in results if ip]
        return active_ips
    def get_device_info(self, ip):
        """获取设备详细信息"""
        try:
            hostname = socket.gethostbyaddr(ip)[0]
        except:
            hostname = "Unknown"
        info = {
            'ip': ip,
            'hostname': hostname,
            'mac': self.get_mac_from_arp(ip)
        }
        return info
    def get_mac_from_arp(self, ip):
        """从ARP表获取MAC地址"""
        try:
            arp_cmd = subprocess.run(['arp', '-n', ip], 
                                    capture_output=True, text=True)
            mac = arp_cmd.stdout.split()[2]
            return mac
        except:
            return "Unknown"
    def scan(self):
        """执行完整扫描"""
        print(f"开始扫描 {self.subnet} ...")
        active_ips = self.ping_sweep()
        if not active_ips:
            print("未发现活跃设备")
            return
        print(f"发现 {len(active_ips)} 个活跃设备:")
        print("-" * 60)
        for ip in active_ips:
            if ip != socket.gethostbyname(socket.gethostname()):
                info = self.get_device_info(ip)
                print(f"IP: {info['ip']:20} MAC: {info['mac']:20} Hostname: {info['hostname']}")
if __name__ == "__main__":
    scanner = NetworkScanner("192.168.1.0/24")
    scanner.scan()

使用建议

  1. 选择合适的方法

    • 局域网内设备发现:使用ARP扫描
    • 网络设备管理:使用Netmiko/SNMP
    • 快速检查:使用ping扫描
  2. 权限要求

    • ARP扫描需要root/sudo权限
    • 网络设备管理需要登录凭证
  3. 性能优化

    • 使用线程/异步提高扫描速度
    • 合理设置超时时间
  4. 安全性

    • 确保扫描行为符合企业政策
    • 仅在授权范围内使用

根据你的具体需求选择合适的方法,如需更多定制化功能可以进一步说明。

抱歉,评论功能暂时关闭!