Ping脚本-如果响应

时间:2018-11-07 23:49:31

标签: python if-statement

由于我刚开始学习python,我只是试图将一个简单的服务器启动/关闭脚本组合在一起。

下面是脚本...但是我无法获取它来输出Server Down部分的代码。我猜是if response == 0收到了“无法到达目的地”响应,并且做出了误报。

该如何解决?

# 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 * "-")

1 个答案:

答案 0 :(得分:0)

response = os.system("echo ping -a -c 1 " + hostname1)

您正在执行的系统命令只是一个echo,它将仅向标准输出打印“ ping -a -c 1 <hostname>”,然后返回0。它实际上并没有执行任何ping操作。您可以通过直接在终端上运行系统命令并检查返回值来对其进行测试:

$ echo ping -a -c 1 8.8.8.8 
ping -a -c 1 8.8.8.8
$ echo $?  # returns 0
$ echo ping -a -c 1 <some.invalid.ip> 
<some.invalid.ip>
$ echo $?  # still returns 0

您应该删除echo并执行以下操作:

response = os.system("ping -a -c 1 " + hostname1)

哪个应该返回正确的结果:

# VALID IP

>>> response = os.system("ping -a -c 1 8.8.8.8")
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=5.80 ms

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 5.803/5.803/5.803/0.000 ms
>>> print(response)
0

# INVALID IP

>>> response = os.system("ping -a -c 1 5.5.5.5")
PING 5.5.5.5 (5.5.5.5) 56(84) bytes of data.

--- 5.5.5.5 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

>>> print(response)
256

对于系统调用,我建议改用subprocess软件包,该软件包包括subprocess.run函数,该函数可以打印命令输出,然后返回包含命令返回代码的对象。

# VALID IP

>>> response = subprocess.run(["ping", "-c", "1", "8.8.8.8"])
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=119 time=5.19 ms

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 5.194/5.194/5.194/0.000 ms
>>> response.returncode
0

# INVALID IP

>>> response = subprocess.run(["ping", "-c", "1", "5.5.5.5"])
PING 5.5.5.5 (5.5.5.5) 56(84) bytes of data.

--- 5.5.5.5 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

>>> response.returncode
1

如果您想隐藏ping命令的输出,可以将subprocess.PIPE传递到stdout的{​​{1}}:

subprocess.run

os.system doc中注明了使用>>> response = subprocess.run(["ping", "-c", "1", "5.5.5.5"], stdout=subprocess.PIPE) >>> response.returncode 1 的建议:

  

subprocess模块提供了更强大的生成工具   新流程并检索其结果;使用该模块是   最好使用此功能。请参阅Replacing Older Functions with the subprocess Module文档中的subprocess部分以了解   一些有用的食谱