python ping

前提:最近需要检测大量IP的联通状态,尝试了多种方法,最终选择了使用系统的ping

第一种pythonping

安装

pip install pythonping

使用

from pythonping import ping

res = ping('1.1.1.1')

if 'Request timed out' in str(res):
        不通
else:
      通

使用很简单,但是缺点也很明显:需要root权限,不满足我的需求

第二种tcping

安装

pip install tcping

使用

from tcping import Ping

ping = Ping(ip, port=22)
ping.ping(1)
ret = ping.result.raw
retlist = list(ret.split('\n'))
success = retlist[2].split(',')[1].split(' ')[1]
success 为1时通,为0时不通

这个使用也很简单,而且也不需要root权限,但是这个有一个明显的特点:需要端口,而且默认是80,
所以也不满足我们的需求。

第三种使用系统ping

import platform
import subprocess

# windowns系统需要特殊处理

params = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', params, '1', ip]

if subprocess.call(command) == 0:
    通
else:
  不通
posted @ 2023-07-27 09:23  yingzi__block  阅读(104)  评论(0编辑  收藏  举报