IPV4 跨网段扫描获取IP地址 python
程序员文章站
2024-02-14 15:14:16
...
#!/usr/bin/env python
#-*- coding:utf-8 -*-
############################
"""
date: 2021年9月26日16:43:54
"""
import platform
import os
import time
import _thread
ip_list = []
class GET_IP_LIST():
"""
IPV4 跨网段扫描获取IP地址
"""
@staticmethod
def get_os():
"""
get os 类型
"""
wos = platform.system()
if wos == "Windows":
return "n"
else:
return "c"
def ping_ip(self,ip_str):
""" IP列表"""
global ip_list
cmd = ["ping", "-{op}".format(op=self.get_os()),
"1", ip_str]
output = os.popen(" ".join(cmd)).readlines()
flag = False
for line in list(output):
if not line:
continue
if str(line).upper().find("TTL") >= 0:
flag = True
break
if flag:
ip_list.append(ip_str)
print("ip: %s is ok ***" % ip_str)
def find_ip(self,ip_prefix,head,tail):
""" 循环处理 休眠0.05秒"""
for i in range(int(head),int(tail)):
ip = '%s.%s' % (ip_prefix,i)
_thread.start_new_thread(self.ping_ip, (ip,))
time.sleep(0.05)
def print_ip_list(self,com_mand):
""" 程序 运行 入口 """
global ip_list
try:
ip_prefix_list = []
ip_list.clear()
ip_h_t_list = []
now = time.strftime('%Y-%m-%d %X', time.localtime())
print("start time %s" % now)
for ip_num in com_mand:
args = "".join(ip_num)
ip_prefix = '.'.join(args.split('.')[:-1])
ip_tail = '.'.join(args.split('.')[-1:])
ip_h_t_list.append(ip_tail)
ip_prefix_list.append(ip_prefix)
for x in ip_prefix_list:
self.find_ip(x, ip_h_t_list[0], ip_h_t_list[1])
now = time.strftime('%Y-%m-%d %X', time.localtime())
print("end time %s" % now)
return ip_list
except Exception as e:
print('print_ip_list_error: ',e)
if __name__ == "__main__":
GET_ip = GET_IP_LIST()
# IPV4 从"192.168.1.1"到 "192.168.9.255" 扫描返回IP列表
com_mand_args = ["192.168.9.1", "192.168.9.255"]
print(GET_ip.print_ip_list(com_mand_args))
上一篇: SpringBoot使用WebSocket的方法实例详解
下一篇: MVC架构的理解