简体   繁体   English

Python Function 测试ping

[英]Python Function to test ping

I'm trying to create a function that I can call on a timed basis to check for good ping and return the result so I can update the on-screen display.我正在尝试创建一个 function,我可以定时调用它来检查 ping 是否正常并返回结果,以便我可以更新屏幕显示。 I am new to python so I don't fully understand how to return a value or set a variable in a function.我是 python 的新手,所以我不完全了解如何在 function 中返回值或设置变量。

Here is my code that works:这是我的有效代码:

import os
hostname = "google.com"
response = os.system("ping -c 1 " + hostname)
if response == 0:
    pingstatus = "Network Active"
else:
    pingstatus = "Network Error"

Here is my attempt at creating a function:这是我创建 function 的尝试:

def check_ping():
    hostname = "google.com"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

And here is how I display pingstatus :这是我显示pingstatus的方式:

label = font_status.render("%s" % pingstatus, 1, (0,0,0))

So what I am looking for is how to return pingstatus from the function. Any help would be greatly appreciated.所以我正在寻找的是如何从 function 返回 pingstatus。任何帮助将不胜感激。

It looks like you want the return keyword看起来你想要return关键字

def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:您需要在一个变量中捕获/“接收”函数(pingstatus)的返回值,例如:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n注意: ping -c适用于 Linux,对于 Windows 使用ping -n

Some info on python functions:关于python函数的一些信息:

http://www.tutorialspoint.com/python/python_functions.htm http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions http://www.learnpython.org/en/Functions

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals.阅读一本很好的 Python 入门教程可能是值得的,该教程将涵盖所有基础知识。 I recommend investigating Udacity.com and codeacademy.com我建议调查Udacity.comcodeacademy.com

Here is a simplified function that returns a boolean and has no output pushed to stdout:这是一个简化的函数,它返回一个布尔值并且没有推送到 stdout 的输出:

import subprocess, platform
def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)

    except Exception, e:
        return False

    return True

Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":添加其他答案,您可以检查操作系统并决定是使用“-c”还是“-n”:

import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + host)

This will work on Windows, OS X, and Linux这将适用于 Windows、OS X 和 Linux

You can also use sys :您还可以使用sys

import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if  sys.platform().lower()=="win32" else "-c 1 ") + host)

Try this尝试这个

def ping(server='example.com', count=1, wait_sec=1):
    """

    :rtype: dict or None
    """
    cmd = "ping -c {} -W {} {}".format(count, wait_sec, server).split(' ')
    try:
        output = subprocess.check_output(cmd).decode().strip()
        lines = output.split("\n")
        total = lines[-2].split(',')[3].split()[1]
        loss = lines[-2].split(',')[2].split()[0]
        timing = lines[-1].split()[3].split('/')
        return {
            'type': 'rtt',
            'min': timing[0],
            'avg': timing[1],
            'max': timing[2],
            'mdev': timing[3],
            'total': total,
            'loss': loss,
        }
    except Exception as e:
        print(e)
        return None

I got a problem in Windows with the response destination host unreachable , because it returns 0 .我在 Windows 中遇到问题,响应destination host unreachable ,因为它返回0

Then, I did this function to solve it, and now it works fine.然后,我做了这个 function 来解决它,现在它工作正常。

import os
import platform

def check_ping(hostname, attempts = 1, silent = False):
    parameter = '-n' if platform.system().lower()=='windows' else '-c'
    filter = ' | findstr /i "TTL"' if platform.system().lower()=='windows' else ' | grep "ttl"'
    if (silent):
        silent = ' > NUL' if platform.system().lower()=='windows' else ' >/dev/null'
    else:
        silent = ''
    response = os.system('ping ' + parameter + ' ' + str(attempts) + ' ' + hostname + filter + silent)

    if response == 0:
        return True
    else:
        return False

Now I can call the command:现在我可以调用命令:

print (check_ping('192.168.1.1', 2, False))

The first parameter is the host The second is the number of requests.第一个参数是host 第二个是请求数。 The third is if you want to show the ping responses or not第三个是是否要显示 ping 响应

This function will test ping for given number of retry attempts and will return True if reachable else False -此函数将测试给定重试次数的 ping,如果可达,则返回 True,否则返回 False -

def ping(host, retry_packets):
    """Returns True if host (str) responds to a ping request."""

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower() == 'windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, str(retry_packets), host]
    return subprocess.call(command) == 0

# Driver Code
print("Ping Status : {}".format(ping(host="xx.xx.xx.xx", retry_packets=2)))

Output :输出 :

Pinging xx.xx.xx.xx with 32 bytes of data:
Reply from xx.xx.xx.xx: bytes=32 time=517ms TTL=60
Reply from xx.xx.xx.xx: bytes=32 time=490ms TTL=60

Ping statistics for xx.xx.xx.xx:
     Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
     Minimum = 490ms, Maximum = 517ms, Average = 503ms
Ping Status : True

Note : Change xx.xx.xx.xx with your IP注意:将xx.xx.xx.xx更改为您的 IP

import platform
import subprocess

def myping(host):
parameter = '-n' if platform.system().lower()=='windows' else '-c'

command = ['ping', parameter, '1', host]
response = subprocess.call(command)

if response == 0:
    return True
else:
    return False
    
print(myping("www.google.com"))

This is my version of check ping function.这是我的检查 ping 功能版本。 May be if well be usefull for someone:可能对某人有用:

def check_ping(host):
if platform.system().lower() == "windows":
response = os.system("ping -n 1 -w 500 " + host + " > nul")
if response == 0:
return "alive"
else:
return "not alive"
else:
response = os.system("ping -c 1 -W 0.5" + host + "> /dev/null")
if response == 1:
return "alive"
else:
return "not alive"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM