Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何检测输出是什么,并从中执行if语句?_Python_If Statement_Cmd_Os.system - Fatal编程技术网

Python 如何检测输出是什么,并从中执行if语句?

Python 如何检测输出是什么,并从中执行if语句?,python,if-statement,cmd,os.system,Python,If Statement,Cmd,Os.system,基本上,我正在用Python编写一个脚本,用于检查服务器的状态。我需要它ping五个不同的IP,然后检测输出是什么。然后我需要一个if语句,例如: import.os Server1 = os.system('ping 123.123.123.123') if Server1 == 'Request timed out': print('Server 1 is down.') else: print('Server 1 is up.') 我不知道该怎么做。让我知道 谢谢。您

基本上,我正在用Python编写一个脚本,用于检查服务器的状态。我需要它ping五个不同的IP,然后检测输出是什么。然后我需要一个if语句,例如:

import.os
Server1 = os.system('ping 123.123.123.123')
if Server1 == 'Request timed out':
     print('Server 1 is down.')
else:
     print('Server 1 is up.')
我不知道该怎么做。让我知道


谢谢。

您在这里发布了大X/Y。你想做X。你不知道如何做X。你认为Y是做X的最好方式,并且正在询问Y。如果你想知道X,请参阅

我会回答Y,但让你知道Y不是最好的方式

import subprocess
import locale

encoding = locale.getdefaultlocale()[1]
proc = subprocess.Popen(["ping", "123.123.123.123"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
if 'Request timed out' in out.decode(encoding):
    print 'the host is down'
else: 
    print 'the host is up'

然后,您需要决定主机停机和开机时的具体操作。

此操作的可能副本工作正常。但我该如何解析它?@user2934716这取决于输出。请更新输出ping在成功和失败时给您的问题。此输出意味着服务器已启动:b'\r\n正在使用32字节的数据复制123.123.123.123.123:\r\n从123.123.123.123复制:字节=32时间=230ms TTL=44\r\n从123.123.123.123复制:字节=32时间=230ms TTL=44\r\n从123.123.123.123.123复制:字节=32time=233ms TTL=44\r\n从123.123.132.123返回:bytes=32 time=233ms TTL=44\r\n\r\n输入123.123.123的统计信息:\r\n数据包:发送=4,接收=4,丢失=0(0%丢失),\r\n以毫秒为单位的近似往返时间:\r\n最小值=230ms,最大值=233ms,平均值=231ms\r\n(下一条注释的第二部分)这意味着服务器已关闭。

b'\r\n使用32字节的数据复制123.123.123.123:\r\n请求超时。\r\n请求超时。\r\n请求超时。\r\n请求超时。\r\n\r\n复制123.123.123的统计信息:\r\n数据包:发送=4,接收=0,丢失=4(100%丢失),\r\n'

有什么想法吗?
ping
在工作连接上出现一些超时是很正常的。也许更好的检查<代码>从回复(因此,如果所有数据包丢失),它只会考虑“主机下”。