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

时间:2018-06-26 12:53:42

标签: python linux

我正在编写一个python脚本,以使用Linux中的IP模块通过 ping 一个subprocess地址来计算数据包丢失CSV文件中保留了多个IP地址。仅提供可ping目标时,它运行良好。
但是,如果在IP文件中给定不可ping CSV,然后脚本退出而不检查该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 个答案:

答案 0 :(得分:1)

如果您的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 :(得分:0)

尝试以下代码:

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))