使用Python写的一个局域网计算机扫描程序,基于模块:ipaddress,ping3,subprocess,re,prettytable,threading

29 篇文章 1 订阅
24 篇文章 0 订阅

使用Python写的一个局域网计算机扫描程序

使用Python写的一个局域网计算机扫描程序,本程序为提升速度使用了多线程,基于模块:ipaddress,ping3,subprocess,re,prettytable,threading
程序可扫描指定IP范围的在线情况与检测目标主机的计算机名称,以表格形式打印出来。
程序非常实用,易于理解,敬请参考。

模块

ipaddress,ping3,subprocess,re,prettytable,threading

代码

import ipaddress
from ping3 import ping
import subprocess
import re
import prettytable
start="192.168.1.1"
end="192.168.1.200"
import threading
def get_ip_span(start,end):
    start=ipaddress.ip_address(start)
    end=ipaddress.ip_address(end)
    ipspan=[]
    ipaddr=start
    while ipaddr<=end:
        ipspan.append(str(ipaddr))
        ipaddr+=1
    return ipspan
def get_hostname(ip):
    cmd=subprocess.check_output("ping -a -n 1 {}".format(ip))
    cmd=cmd.decode("gbk")
    if cmd:
        lines=cmd.split("\n")
        l1=lines[1]
        pattern=".*Ping (.*) \["
        names=re.findall(pattern,l1)
        return names[0]
class Scan(threading.Thread):
    def __init__(self,ip,data:list):
        self.ip=ip
        self.data=data
        threading.Thread.__init__(self)
    def run(self):
        delay = ping(dest_addr=self.ip, timeout=0.3)
        if delay:
            delay = int(delay * 1000)
            try:
                hn = get_hostname(self.ip)
            except:
                hn = "unknown"
            print("{}, 在线, 名称: {}".format(self.ip, hn))
            self.data.append((self.ip, hn, delay))
        else:
            print("{}, 不在线".format(self.ip))
ipaddrs=get_ip_span(start,end)
pt=prettytable.PrettyTable(field_names=("IP","机器名","延时"))
data=[]
thread=[]
def check_thread_alive():
    for th in thread:
        if th.is_alive():
           return True
for ip in ipaddrs:
    th=Scan(ip=ip,data=data)
    th.start()
    thread.append(th)

while 1:
    if not check_thread_alive():
        break
for row in data:
    pt.add_row(row)
print(pt)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值