简化并减少显示的不需要的输出

时间:2017-02-16 18:27:03

标签: python ping

这是我检查与主机关联的状态的代码,我只想打印状态(向上/向下)并避免在终端上显示整个ping过程。

import os
hostname = "google.com"
response = os.system("ping -c 1" + hostname)

if response == 0:
    print hostname, 'up'
else:
    print hostname, 'down'

2 个答案:

答案 0 :(得分:0)

你好,我做了一个这样的。 稍后我会定制这个以发送电子邮件。

我告诉你。 的问候,

导入操作系统    hostname =“google.com”

如果os.name =='nt'或os.name =='NT':        response = os.system(“ping -n 1”+ hostname)    其他:        response = os.system(“ping -c 1”+ hostname)

如果响应== 0:        打印(主机名,'上')    其他:        print(主机名,'down')        '''如果ping失败,则添加选项以发送电子邮件''

答案 1 :(得分:0)

import subprocess 
import re
hostname = "google.com"  

with subprocess.Popen(["ping", "-c 1", "-t 3", hostname], stdout=subprocess.PIPE) as proc:
  match = re.findall(r'1 packets received', proc.stdout.read().decode())
  if match:
    print(hostname + ' is up')
  else:
    print(hostname + ' is down')

结果:

google.com is up

对于python 2.7:

test = subprocess.Popen(["ping", "-c 1", "-t 3", hostname],stdout=subprocess.PIPE)
match = re.findall(r'1 packets received', test.communicate()[0])
if match:
  print(hostname + ' is up')
else: 
  print(hostname + ' is down')