python 批量ping服务器
最近在https://pypi.python.org/pypi/mping/0.1.2找到了一个python包,可以用它来批量ping服务器,它是中国的大神写的,支持单个服务器、将服务器IP写在txt或json里都可以。
这里我改了几个字,方便我这种英文不好的同学使用
mping.py
#!/usr/bin/env python3
# coding: utf-8 import argparse
import ctypes
import json
import os
import random
import re
import select
import socket
import struct
import sys
import threading
import time if sys.platform.startswith('win32'):
clock = time.clock
run_as_root = ctypes.windll.shell32.IsUserAnAdmin() != 0
else:
clock = time.time
run_as_root = os.getuid() == 0 DEFAULT_DURATION = 3 EXIT_CODE_BY_USER = 1
EXIT_CODE_DNS_ERR = 2
EXIT_CODE_IO_ERR = 3 # Credit: https://gist.github.com/pyos/10980172
def chk(data):
x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
x = (x >> 16) + (x & 0xFFFF)
x = (x >> 16) + (x & 0xFFFF)
return struct.pack('<H', ~x & 0xFFFF) # From the same gist commented above, with minor modified.
def ping(addr, timeout=1, udp=not run_as_root, number=1, data=b''):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM if udp else socket.SOCK_RAW, socket.IPPROTO_ICMP) as conn:
payload = struct.pack('!HH', random.randrange(0, 65536), number) + data conn.connect((addr, 80))
conn.sendall(b'\x08\0' + chk(b'\x08\0\0\0' + payload) + payload)
start = clock() while select.select([conn], [], [], max(0, start + timeout - clock()))[0]:
data = conn.recv(65536)
if data[20:] == b'\0\0' + chk(b'\0\0\0\0' + payload) + payload:
return clock() - start class PingResults(list):
def __init__(self, multiply=1000):
"""
A list to save ping results, and can be used to count min/avg/max, etc.
:param multiply: Every valid result will be multiplied by this number.
"""
super(PingResults, self).__init__()
self.multiple = multiply def append(self, rtt):
"""
To receive a ping result, accept a number for how long the single ping took, or None for timeout.
:param rtt: The ping round-trip time.
"""
if rtt is not None and self.multiple:
rtt *= self.multiple
return super(PingResults, self).append(rtt) @property
def valid_results(self):
return list(filter(lambda x: x is not None, self)) @property
def valid_count(self):
return len(self.valid_results) @property
def loss_rate(self):
if self:
return 1 - len(self.valid_results) / len(self) @property
def min(self):
if self.valid_results:
return min(self.valid_results) @property
def avg(self):
if self.valid_results:
return sum(self.valid_results) / len(self.valid_results) @property
def max(self):
if self.valid_results:
return max(self.valid_results) @property
def form_text(self):
if self.valid_results:#调整结果数据之间的间隔
return '{0.valid_count}, {0.loss_rate:.1%}, {0.min:.1f}/{0.avg:.1f}/{0.max:.1f}'.format(self)
elif self:
return '不通'
else:
return 'EMPTY' def __str__(self):
return self.form_text def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.form_text) class PingTask(threading.Thread):
def __init__(self, host, timeout, interval):
"""
A threading.Thread based class for each host to ping.
:param host: a host name or ip address
:param timeout: timeout for each ping
:param interval: the max time to sleep between each ping
""" self.host = host if re.match(r'(?:\d{1,3}\.){3}(?:\d{1,3})$', host):
self.ip = host
else:
print('Resolving host: {}'.format(host))
try:
self.ip = socket.gethostbyname(host)
except socket.gaierror:
print('Unable to resolve host: {}'.format(host))
exit(EXIT_CODE_DNS_ERR) self.timeout = timeout
self.interval = interval self.pr = PingResults()
self.finished = False super(PingTask, self).__init__() def run(self):
while not self.finished:
try:
rtt = ping(self.ip, timeout=self.timeout)
except OSError:
print('Unable to ping: {}'.format(self.host))
break
self.pr.append(rtt)
escaped = rtt or self.timeout
if escaped < self.interval:
time.sleep(self.interval - escaped) def finish(self):
self.finished = True def mping(hosts, duration=DEFAULT_DURATION, timeout=1.0, interval=0.0, quiet=False, sort=True):
"""
Ping hosts in multi-threads, and return the ping results.
:param hosts: A list of hosts, or a {name: host, ...} formed dict. A host can be a domain or an ip address
:param duration: The duration which pinging lasts in seconds
:param timeout: The timeout for each single ping in each thread
:param interval: The max time to sleep between each single ping in each thread
:param quiet: Do not print results while processing
:param sort: The results will be sorted by valid_count in reversed order if this param is True
:return: A list of PingResults
""" def results(_tasks, _sort=True):
"""
Return the current status of a list of PingTask
"""
r = list(zip(heads, [t.pr for t in _tasks]))
if _sort:
r.sort(key=lambda x: x[1].valid_count, reverse=True)
return r if isinstance(hosts, list):
heads = hosts
elif isinstance(hosts, dict):
heads = list(hosts.items())
hosts = hosts.values()
else:
type_err_msg = '`hosts` should be a host list, or a {name: host, ...} formed dict.'
raise TypeError(type_err_msg) try:
tasks = [PingTask(host, timeout, interval) for host in hosts]
except KeyboardInterrupt:
exit(EXIT_CODE_BY_USER)
else:
doing_msg = 'Pinging {} hosts'.format(len(hosts))
if duration > 0:
doing_msg += ' within {} seconds'.format(int(duration))
doing_msg += '...' if quiet:
print(doing_msg) for task in tasks:
task.start() try:
start = clock()
while True: if duration > 0:
remain = duration + start - clock()
if remain > 0:
time.sleep(min(remain, 1))
else:
break
else:
time.sleep(1) if not quiet:
print('\n{}\n{}'.format(
results_string(results(tasks, True)[:10]),
doing_msg)) except KeyboardInterrupt:
print()
finally:
for task in tasks:
task.finish() # Maybe not necessary?
# for task in tasks:
# task.join() return results(tasks, sort) def table_string(rows):
rows = list(map(lambda x: list(map(str, x)), rows))
widths = list(map(lambda x: max(map(len, x)), zip(*rows)))
rows = list(map(lambda y: ' | '.join(map(lambda x: '{:{w}}'.format(x[0], w=x[1]), zip(y, widths))), rows))
rows.insert(1, '-|-'.join(list(map(lambda x: '-' * x, widths))))
return '\n'.join(rows) def results_string(prs):
named = True if isinstance(prs[0][0], tuple) else False
rows = [['IP', '有效次数 , 丢包率% , min/avg/max']]
if named:
rows[0].insert(0, 'name') for head, pr in prs:
row = list()
if named:
row.extend(head)
else:
row.append(head)
row.append(pr.form_text)
rows.append(row)
return table_string(rows) def main():
ap = argparse.ArgumentParser(
description='Ping multiple hosts concurrently and find the fastest to you.',
epilog='A plain text file or a json can be used as the -p/--path argument: '
'1. Plain text file: hosts in lines; '
'2. Json file: hosts in a list or a object (dict) with names.') ap.add_argument(
'hosts', type=str, nargs='*',
help='a list of hosts, separated by space') ap.add_argument(
'-p', '--path', type=str, metavar='path',
help='specify a file path to get the hosts from') ap.add_argument(
'-d', '--duration', type=float, default=DEFAULT_DURATION, metavar='secs',
help='the duration how long the progress lasts (default: {})'.format(DEFAULT_DURATION)) ap.add_argument(
'-i', '--interval', type=float, default=0.0, metavar='secs',
help='the max time to wait between pings in each thread (default: 0)') ap.add_argument(
'-t', '--timeout', type=float, default=1.0, metavar='secs',
help='the timeout for each single ping in each thread (default: 1.0)') ap.add_argument(
'-a', '--all', action='store_true',
help='show all results (default: top 10 results)'
', and note this option can be overridden by -S/--no_sort') ap.add_argument(
'-q', '--quiet', action='store_true',
help='do not print results while processing (default: print the top 10 hosts)'
) ap.add_argument(
'-S', '--do_not_sort', action='store_false', dest='sort',
help='do not sort the results (default: sort by ping count in descending order)') args = ap.parse_args() hosts = None
if not args.path and not args.hosts:
ap.print_help()
elif args.path:
try:
with open(args.path) as fp:
hosts = json.load(fp)
except IOError as e:
print('Unable open file:\n{}'.format(e))
exit(EXIT_CODE_IO_ERR)
except json.JSONDecodeError:
with open(args.path) as fp:
hosts = re.findall(r'^\s*([a-z0-9\-.]+)\s*$', fp.read(), re.M)
else:
hosts = args.hosts if not hosts:
exit() results = mping(
hosts=hosts,
duration=args.duration,
timeout=args.timeout,
interval=args.interval,
quiet=args.quiet,
sort=args.sort
) if not args.all and args.sort:
results = results[:10] if not args.quiet:
print('\n********最终检查结果:*************************\n') print(results_string(results)) if __name__ == '__main__':
main()
python 批量ping服务器的更多相关文章
- Python批量检测服务器端口可用性与Socket函数使用
socket函数 简述 socket又称套间字或者插口,是网络通信中必不可少的工具.有道是:"无socket,不网络".由于socket最早在BSD Unix上使用,而Unix/L ...
- saltstack+python批量修改服务器密码
saltstack安装:略过 python脚本修改密码: # -*- coding utf-8 -*- import socket import re import os import sys imp ...
- 使用Python批量更新服务器文件【新手必学】
买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦,虽然还有git的h ...
- Python批量扫描服务器指定端口状态
闲来无事用Python写了一个简陋的端口扫描脚本,其简单的逻辑如下: 1. python DetectHostPort.py iplist.txt(存放着需要扫描的IP地址列表的文本,每行一个地址) ...
- python 批量ping脚本不能用os.system
os.system(cmd)通过执行命令会得到返回值. ping通的情况下返回值为0. ping不通的情况: 1.请求超时,返回值1 2.无法访问目标主机,返回值为 0,和ping通返回值相同 所 ...
- shell脚本和python脚本实现批量ping IP测试
先建一个存放ip列表的txt文件: [root@yysslopenvpn01 ~]# cat hostip.txt 192.168.130.1 192.168.130.2 192.168.130.3 ...
- Shell学习笔记之shell脚本和python脚本实现批量ping IP测试
0x00 将IP列表放到txt文件内 先建一个存放ip列表的txt文件: [root@yysslopenvpn01 ~]# cat hostip.txt 192.168.130.1 192.168.1 ...
- python实现本地批量ping多个IP
本文主要利用python的相关模块进行批量ping ,测试IP连通性. 下面看具体代码(python3): #!/usr/bin/env python#-*-coding:utf-8-*- impor ...
- 使用Python实现批量ping操作
在日常的工作中,我们通常会有去探测目标主机是否存活的应用场景,单个的服务器主机可以通过计算机自带的DOS命令来执行,但是业务的存在往往不是单个存在的,通常都是需要去探测C段的主机(同一个网段下的存活主 ...
随机推荐
- 21天学通C++学习笔记(三):变量和常量
1. 简述 内存是一种临时存储器,也被称为随机存取存储器(RAM),所有的计算机.智能手机及其他可编程设备都包含微处理器和一定数量的内存,用地址来定位不同的存储区域,像编号一样. 硬盘可以永久的存储数 ...
- I-team 博客全文检索 Elasticsearch 实战
一直觉得博客缺点东西,最近还是发现了,当博客慢慢多起来的时候想要找一篇之前写的博客很是麻烦,于是作为后端开发的楼主觉得自己动手丰衣足食,也就有了这次博客全文检索功能Elasticsearch实战,这里 ...
- Web标准及网站的可用性、可访问性
学习前端的过程中到处充斥着Web标准.可用性.可访问性这些词,那么到底它们指的是什么呢? 一.什么是Web标准 简单的说,Web标准就是我们在学习前端中接触最多的HTML.CSS.JavaScript ...
- IP地址和子网划分
前期知识准备 二进制 和十进制 二进制数据是用0和1表示的数,进位规则为缝二进1, 二进制和十进制的关系 二进 十进 0 1 10 2 100 4 1000 8 10000 16 10000 ...
- 在一个java类里,private int a; 什么时候要使用integer
private Integer index; if(index == null) index = 0; else this.index = index; Integer有一个明显的好处,就是它能比in ...
- 5、C++结构体的使用
5.结构体定义 结构体是用户带定义的类型,而结构声明定义了这种类型的数据属性.定义了类型后,便可以创建这种类型的变量,因此创建结构包括两步.首先,定义结构描述——它描述并标记了能够存储在结构中的各种数 ...
- js 删除removeChild与替换replaceChild
<input type="button" value="删除" id="btn" /> <input type=" ...
- WPF:CheckBox竖向的滑块效果
原文:WPF:CheckBox竖向的滑块效果 之前做了一个横向的滑块效果,<WPF:CheckBox滑块效果>,其实我觉得那个不好看,今天又做了一个竖向的玩. <Style Targ ...
- 洛谷 P2330 [SCOI2005]繁忙的都市(最小生成树)
嗯... 题目链接:https://www.luogu.org/problemnew/show/P2330 这道题的问法也实在是太模板了吧: 1.改造的道路越少越好 2.能够把所有的交叉路口直接或间接 ...
- scrapy的 安装 及 流程 转
安装 linux 和 mac 直接 pip install scrapy 就行 windows 安装步骤 a. pip3 install wheel b. 下载twist ...