我只是在尝试编写一个简单的服务器启动/关闭脚本,因为我刚刚开始学习python。在
以下是脚本。。。但是我不能让它输出服务器的代码段。我猜if response == 0
收到了“Destination Unreachable”响应,并做出了一个假阳性。在
我能做些什么来避开这个问题?在
# Server up/down Script
import os
hostname1 = input (" Please Enter IP Address: ")
response = os.system("echo ping -a -c 1 " + hostname1)
#and then check the response...
if response == 0: # This will check the host repeatedly
print (hostname1, '\033[1;32m [ **SERVER ALIVE** ] \033[1;m')
# As long as the server is up it will print the UP response in green text
else:
print(hostname1, '[ **SERVER DOWN** ]')
print( 30 * "-")
您正在执行的系统命令只是一个^{} ,它只会将“
^{pr2}$ping -a -c 1 <hostname>
”打印到stdout,然后返回0。它实际上不做任何ping操作。您可以直接在终端上运行系统命令并检查返回值:{cd1>你应该删除:
它应该返回正确的结果:
对于系统调用,我建议改用^{} 包,它包含^{} 函数,该函数可以打印命令输出,然后返回包含命令返回代码的对象。在
如果要隐藏
ping
命令的输出,可以将subprocess.PIPE
传递给subprocess.run
的stdout
:使用} doc 中注明:
subprocess
的建议在^{相关问题 更多 >
编程相关推荐