python写ping工具_python实现ping

os.system和os.popen的区别:

os.system 返回值 int类型 0 或者 1, 不需要print直接将结果输出

a = os.system('ping 8.8.8.8')

print(type(a))

Pinging 8.8.8.8 with 32 bytes of data:

Reply from 8.8.8.8: bytes=32 time=37ms TTL=114

Reply from 8.8.8.8: bytes=32 time=38ms TTL=114

Reply from 8.8.8.8: bytes=32 time=37ms TTL=114

Reply from 8.8.8.8: bytes=32 time=38ms TTL=114

Ping statistics for 8.8.8.8:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 37ms, Maximum = 38ms, Average = 37ms

os.open 的返回值是一个对象,需要借助read()方法来 读取输出

b = os.popen('ping 8.8.8.8')

print(type(b))

print(b.read())

Pinging 8.8.8.8 with 32 bytes of data:

Reply from 8.8.8.8: bytes=32 time=38ms TTL=114

Reply from 8.8.8.8: bytes=32 time=37ms TTL=114

Reply from 8.8.8.8: bytes=32 time=37ms TTL=114

Reply from 8.8.8.8: bytes=32 time=37ms TTL=114

Ping statistics for 8.8.8.8:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 37ms, Maximum = 38ms, Average = 37ms

os.system例子:

import os

hostname = "google.com" #example

response = os.system("ping -c 1 " + hostname)

#and then check the response...

if response == 0:

print (hostname, 'is up!')

else:

print (hostname, 'is down!')

os.popen例子:

import os

ip_list = ['8.8.8.8','1.1.1.1','4.4.4.4']

for ip in ip_list:

response = os.popen(f"ping {ip}").read()

if "Received = 4" in response:

print(f"UP {ip} ping Successful")

else:

print(f"DOWN {ip} ping Unsuccessful")

python批量ping

import os

import time

with open('ip-source.txt') as file:

ip_list = file.read().splitlines()

for ip in ip_list:

os.system('cls')

print('pinging now:',ip)

print('-'*60)

os.system('ping -n 2{}'.format(ip))

time.sleep(2)

print('-'*60)

subprocess.Popen

import subprocess

'''servers.txt contains ip address in following format192.168.1.1192.168.1.2'''

with open('servers.txt', 'r') as f:

for ip in f:

result = subprocess.Popen(["ping", "-c", "1", "-n", "-W", "2", ip], stdout=f, stderr=f).wait()

if result:

print(ip, "inactive")

else:

print(ip, "active")

pythonpingpythonping​pypi.org

from pythonping import ping

ping('127.0.0.1', verbose=True)

输出

Reply from 127.0.0.1, 9 bytes in 0.17ms

Reply from 127.0.0.1, 9 bytes in 0.14ms

Reply from 127.0.0.1, 9 bytes in 0.12ms

Reply from 127.0.0.1, 9 bytes in 0.12ms

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值