下面是一个基本的Python脚本示例,用于ping当前网络:
import os
# 获取本机IP地址
def get_ip_address():
with os.popen('ipconfig') as f:
for line in f:
if 'IPv4 Address' in line:
return line.split(':')[-1].strip()
# Ping当前网络
def ping_network():
ip_address = get_ip_address()
print(f"Pinging network from {ip_address}...")
response = os.system(f"ping {ip_address}")
# 检查ping的结果
if response == 0:
print("Ping successful!")
else:
print("Ping failed!")
# 调用ping_network函数
ping_network()
这个脚本首先使用os.popen
命令来执行ipconfig
命令,从而获取本机的IPv4地址。然后,使用os.system
命令来执行ping
命令并将结果存储在response
变量中。最后,根据response
的值判断ping是否成功,并打印相应的消息。
请注意,这个脚本仅适用于Windows操作系统。如果你使用的是其他操作系统,请相应修改获取IP地址的方法。