如何从 subprocess.run() 正确获取结果?

How to properly get the results from subprocess.run()?

很抱歉再次询问这个问题,但我一直无法找到消除不断发生的误报的方法。

当我收到回复时 "Destination unreachable" 回复显示所有返回的数据包和 0 个数据包丢失...所以它显示 SERVER UP 而不是关闭。

我到底该如何解决这个问题?

# Server up/down Script

# - Module Import section
import socket
import sys
import os
import subprocess

# - IP Address input request
hostname1 = input (" Please Enter IP Address: ")

# - Command to run ping request, but also hides ping info
response = subprocess.run(["ping", "-c", "1", hostname1], stdout=subprocess.PIPE)
response.returncode

#___ ORIGINAL CODE ___
#if (response == "Reply from", hostname1):
if response.returncode == 0:
    print ( 50 * "-")
    print ("[ **SERVER IS ALIVE** ]")
    print ( 50 * "-")
elif response.returncode == 0 and (str("Destination host unreachable.")):
    print( 50 * "-")
    print(hostname1, "[ **SERVER DOWN** ] ")
    print( 50 * "-")
else:
    print( 50 * "-")
    print(hostname1, "[ **SERVER DOWN** ] ")
    print( 50 * "-")

代码中的表达式 (str("Destination host unreachable.") 将始终计算为 True——任何非空字符串的真实性。

如果您想查看特定字符串是否在调用子进程产生的 stdout 输出中,您需要使用如下表达式:

("Destination host unreachable." in response.stdout.decode("utf-8"))

response = subprocess.run(...) 调用之后。

这是一个 article describing how to use the subprocess module (note especially the Capturing Output 部分。

# - Import section - below are the modules I will need to call for this script
import socket
import sys
import os
import subprocess
import ctypes
import ipaddress

# - User input request for IP or hostanme
hostname1 = input (" Please Enter IP Address: ")

ip_net = ipaddress.ip_network(hostname1)

# Configure subprocess to hide the console window
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE

output = subprocess.Popen(['ping', '-n', '1', '-w', '500', str(hostname1)], stdout=subprocess.PIPE, startupinfo=info).communicate()[0]

if "Destination host unreachable" in output.decode('utf-8'):
    print ( 50 * "-")
    print (ctypes.windll.user32.MessageBoxW(0, hostname1 +  " [ SERVER OFFLINE ] ", " *** SERVER STATUS - ALERT *** ", 0))
    print ( 50 * "-")
elif "Request timed out" in output.decode('utf-8'):
    print( 50 * "-")
    print(ctypes.windll.user32.MessageBoxW(0, hostname1 + " [ SERVER OFFLINE ] ", "*** SERVER STATUS - ALERT ***", 0))
    print( 50 * "-")
else:
    print( 50 * "-")
    print(ctypes.windll.user32.MessageBoxW(0, hostname1 + " *** SERVER ALIVE *** ", "** SERVER STATUS - ALERT **", 0))
    print( 50 * "-")


#------------------------------------------------------