python - 固定 IP 地址时在 Python 中创建简单的 if 语句

标签 python ip ping

我正在使用:Windows 我正在尝试在 ping IP 地址时创建一个简单的 if 语句

import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)

#and then check the response...
if response == 0:
    print hostname, 'is down'

else:
  print hostname, 'is up'

print response

我对此还很陌生,但无论我输入什么 IP 地址,无论有效与否,它都会说它已启动。

最佳答案

os.system() 返回进程退出值。 0 表示成功。

在您的情况下,它已成功执行,因此返回 0。您所要做的就是从 ping 命令获取完整的输出,然后进行字符串比较以查明该 IP 是否处于事件状态。

您需要使用subprocess's checkoutput method

import subprocess

hostname = "google.com"
batcmd="ping -n 1 " + hostname
result = subprocess.check_output(batcmd, shell=True)
if "Received = 1" in result:
    print "Is UP"
else:
    print "Is Down"

关于python - 固定 IP 地址时在 Python 中创建简单的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191011/

相关文章:

python - 后台进程的 cy.exec 超时

vb.net - 将值从 Default.aspx 传递到 silverlight3 中的应用程序或主页

ruby - Ping ruby 网站?

ruby - 如何仅使用标准套接字库在 Ruby 中实现 ICMP ping?

Windows ping 超时参数似乎不起作用

python - 没有 Sympy 两侧限制吗?

python - 如何在机器人框架中将列表作为命令行参数传递。?

linux - 服务器脚本在不应该发送电子邮件的时候不断发送电子邮件

python - 为什么我的算法越来越慢?

c++ - 如何为Wireshark转储IP数据包缓冲区/如何在C++中进行十六进制转储?