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")
pythonpingpythonpingpypi.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