在Python中调用ping命令可以通过多种方式实现,以下是几种常见的方法:
方法一:使用`subprocess`模块
import subprocessimport platformdef ping_host(ip):根据操作系统选择合适的ping命令command = ["ping", "-c", "1", ip] if platform.system().lower() == "linux" else ["ping", ip]执行ping命令response = subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)判断是否成功if response == 0:print(f"{ip} is reachable.")else:print(f"Failed to reach {ip}.")def batch_ping(ips):for ip in ips:ping_host(ip)
方法二:使用`scapy`库
from scapy.all import *import timedef ping_one(dst="36.152.44.95", ttl_no=64, id_no=345, seq_no=5):start_time = time.time()time_to_bytes = struct.pack(">d", start_time)ping_one_result = sr1(IP(dst=dst, ttl=ttl_no)/ICMP(seq=seq_no, id=id_no)/time_to_bytes, timeout=1, verbose=False)判断收回来的包是不是ICMP的应答包,和序列号是否相同try:if ping_one_result.getlayer('ICMP').type == 0 and ping_one_result.getlayer('ICMP').seq == seq_no:reply_src_IP = ping_one_result.getlayer('IP').srcreturn reply_src_IPexcept AttributeError:return None
方法三:使用第三方库`pythonping`
from pythonping import ping最简单的 pingresponse = ping('www.baidu.com')print(response)指定发送次数response = ping('8.8.8.8', count=3)print(response)

方法四:使用`ping3`库
from ping3 import pingresponse_time = ping('baidu.com')print(f'Response time: {response_time} seconds')
方法五:使用`os`模块
import osdef subping():for i in range(1, 10):ips = f'192.168.2.{i}'ret = os.system(f'ping -n 1 -w 1 {ips}')if ret == 0:print(ips, 'Online')else:print(ips, 'Offline')
注意事项
确保你的Python环境可以执行外部命令。
在Windows上,你可能需要以管理员权限运行脚本。
在Linux或macOS上,可能需要指定正确的命令路径,如`/bin/ping`或`/usr/bin/ping`。
需要确保网络环境允许发送ICMP请求。
以上方法都可以用来执行ping操作,你可以根据自己的需要选择合适的方法。
