Ping a site in Python?

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

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

相关标签:
15条回答
  • 2020-11-22 09:56

    Here's a short snippet using subprocess. The check_call method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using shlex to split the command line arguments.

      import subprocess
      import shlex
    
      command_line = "ping -c 1 www.google.comsldjkflksj"
      args = shlex.split(command_line)
      try:
          subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
          print "Website is there."
      except subprocess.CalledProcessError:
          print "Couldn't get a ping."
    
    0 讨论(0)
  • 2020-11-22 09:56

    using subprocess ping command to ping decode it because the response is binary:

    import subprocess
    ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
    result = ping_response.decode('utf-8')
    print(result)
    
    0 讨论(0)
  • 2020-11-22 09:57

    You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

    #!/usr/bin/env python2.5
    from threading import Thread
    import subprocess
    from Queue import Queue
    
    num_threads = 4
    queue = Queue()
    ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
    #wraps system ping command
    def pinger(i, q):
        """Pings subnet"""
        while True:
            ip = q.get()
            print "Thread %s: Pinging %s" % (i, ip)
            ret = subprocess.call("ping -c 1 %s" % ip,
                shell=True,
                stdout=open('/dev/null', 'w'),
                stderr=subprocess.STDOUT)
            if ret == 0:
                print "%s: is alive" % ip
            else:
                print "%s: did not respond" % ip
            q.task_done()
    #Spawn thread pool
    for i in range(num_threads):
    
        worker = Thread(target=pinger, args=(i, queue))
        worker.setDaemon(True)
        worker.start()
    #Place work in queue
    for ip in ips:
        queue.put(ip)
    #Wait until worker threads are done to exit    
    queue.join()
    

    He is also author of: Python for Unix and Linux System Administration

    http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

    0 讨论(0)
提交回复
热议问题