Ping脚本if respons

2024-04-20 04:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在尝试编写一个简单的服务器启动/关闭脚本,因为我刚刚开始学习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 * "-")

Tags: the服务器脚本ifserverosresponsecheck
1条回答
网友
1楼 · 发布于 2024-04-20 04:26:44
response = os.system("echo ping -a -c 1 " + hostname1)

您正在执行的系统命令只是一个^{},它只会将“ping -a -c 1 <hostname>”打印到stdout,然后返回0。它实际上不做任何ping操作。您可以直接在终端上运行系统命令并检查返回值:

^{pr2}$

{cd1>你应该删除:

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

对于系统调用,我建议改用^{}包,它包含^{}函数,该函数可以打印命令输出,然后返回包含命令返回代码的对象。在

# 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传递给subprocess.runstdout

>>> response = subprocess.run(["ping", "-c", "1", "5.5.5.5"], stdout=subprocess.PIPE)
>>> response.returncode
1

使用subprocess的建议在^{} doc中注明:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes

相关问题 更多 >