# 场景一:获取命令的执行结果 os.popen()
import os
result = os.popen("ping baidu.com")
print(result)
print(result.read())
print(type(result.read()))
#场景二:获取命令的状态码 0-255,0 代表成功,非0代表失败
import subprocess
null_obj = open("win_null",mode="wb")
result = subprocess.call("ping baidu.com",shell=True,stdout=null_obj,stderr=null_obj)
print(result)
null_obj.close()
检测单个地址可正常通信
import subprocess
import threading
def checkIP(ip):
ping_cmd = "ping -n 1 -w 1 %s" % ip
with open("win_null",mode="wb") as fobj:
ping_result = subprocess.call(ping_cmd,shell=True,stdout=fobj,stderr=fobj)
if ping_result == 0:
print("Host %s is up!!!" % ip)
if __name__ == '__main__':
checkIP(ip="192.168.3.1")
# 检测网段在线的主机 192.168.3.0/24
def checkSubNet():
for i in range(1,255):
ip = "192.168.3.%d" % i
#创建现场,执行ping的任务;target=函数名称;args用于给函数传参,数据类型必须是元组
threading.Thread(target=checkIP,args=(ip,))
#checkIP(ip=ip)
if __name__ == '__main__':
checkSubNet()
整数 %d
浮点数 %s
字符串 %s