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段的主机(同一个网段下的存活主 ...
随机推荐
- 微信 oauth2 两次回调
场景: logger.Info("f: " + wx.From); logger.Info("c: " + wx.Code); logger.Info(&quo ...
- PLSQL Developer连接远程Oracle
注:内容来网络 (一)不安装客户端的解决办法. 第一种方法: 1.在安装ORACLE服务器的机器上搜索下列文件, oci.dll ocijdbc10.dll ociw32.dll orannzsbb1 ...
- fwrite()
注:fwrite(),fread -可对数据块读写,且数据为二进制,文本下查看为乱码,文件的打开方式为 “b*” 实例: 写入二进制数据 for (int i = 0; i < SN; i++) ...
- WCF进阶(二)——Contract
前言 我和用户有个约定,这个契约上篇已经说过了,分为服务契约.操作契约.消息契约.数据契约等,说白了,你到底让我看到什么,你告诉我,或者说,我可以让你看到什么,你敢用吗?下面就说一些基础的,关于这个些 ...
- 跟我一起读postgresql源码(二)——Parser(查询分析模块)
上篇博客简要的介绍了下psql命令行客户端的前台代码.这一次,我们来看看后台的代码吧. 十分不好意思的是,上篇博客我们只说明了前台登陆的代码,没有介绍前台登陆过程中,后台是如何工作的.即:后台接到前台 ...
- 6A - Daydreamin
#include <iostream> #include <cstdio> using namespace std; typedef long long ll; ll dp[] ...
- SQL语句之表操作
SQL语句系列 1.SQL语句之行操作 2.SQL语句之表操作 3.SQL语句之数据库操作 4.SQL语句之用户管理 写在前面 在上一篇博文里面我整理了“行”级别的操作,分别是“增(insert).删 ...
- python---day14( 内置函数二)
内置函数二一:匿名函数 lambda函数 lambda 表示匿名函数,不需要用def 来申明. 语法: 函数名=lambda 参数:返回值 ----〉 案例:f=lambda n:n*n 例子01: ...
- C++_函数2-内联函数
内联函数的目的是为了提高程序运行速度所做的一项改进. 常规函数与内联函数的区别不在于编写方式,而在于C++编译器如何将它们组合到程序中. 编译过程的最终产品是:可执行程序,由一组机器语言指令组成.运行 ...
- 基于 Pymsql 数据库连接池
helper.py import pymysql from settings import Config def connect(): conn = Config.POOL.connection() ...