Ping a site in Python?

前端 未结 15 2543
我寻月下人不归
我寻月下人不归 2020-11-22 09:22

How do I ping a website or IP address with Python?

15条回答
  •  青春惊慌失措
    2020-11-22 09:52

    Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.

    import platform,subproccess,re
    def Ping(hostname,timeout):
        if platform.system() == "Windows":
            command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
        else:
            command="ping -i "+str(timeout)+" -c 1 " + hostname
        proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
        matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
        if matches:
            return matches.group(1)
        else: 
            return False
    

提交回复
热议问题