subprocess.CalledProcessError: 针对不可ping通的目标返回了非零退出状态1

3
我正在编写一个Python脚本,使用Linux中的subprocess模块通过ping测试IP地址来计算数据包丢失率。在CSV文件中保存了一个以上的IP地址。当只给出可ping通的目标时,它可以正常运行。
但是,当CSV文件中给出不可ping通的IP时,就会抛出错误并导致脚本退出,无法检查该CSV文件中的其他IP地址。因此,我无法捕获非可ping通目标的数据包丢失率,这是该脚本的主要目的。
请建议下一步操作。
subprocess.check_output(['ping','-c 4',hostname], shell=False, 
universal_newlines=True).splitlines()

subprocess.CalledProcessError: Command '['ping', '-c 4', '192.168.134.100']' returned non-zero exit status 1
2个回答

2

只是当子进程返回错误时,说明您的ping有100%的数据包丢失、目标不可达或其他问题。您可以这样做:

try:
    # subprocess code here
except:
    # some code here if the destination is not pingable, e.g. print("Destination unreachable..") or something else
    pass # You need pass so the script will continue on even after the error

1

Try this Code:

import subprocess
def systemCommand(Command):
    Output = ""
    Error = ""     
    try:
        Output = subprocess.check_output(Command,stderr = subprocess.STDOUT,shell='True')
    except subprocess.CalledProcessError as e:
        #Invalid command raises this exception
        Error =  e.output 

    if Output:
        Stdout = Output.split("\n")
    else:
        Stdout = []
    if Error:
        Stderr = Error.split("\n")
    else:
        Stderr = []

    return (Stdout,Stderr)

#in main
Host = "ip to ping"
NoOfPackets = 2
Timeout = 5000 #in milliseconds
#Command for windows
Command = 'ping -n {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
#Command for linux 
#Command = 'ping -c {0} -w {1} {2}'.format(NoOfPackets,Timeout,Host)
Stdout,Stderr = systemCommand(Command)
if Stdout:
   print("Host [{}] is reachable.".format(Host))
else:
   print("Host [{}] is unreachable.".format(Host))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接