Python 3.5 Async&等待Ping

时间:2016-08-16 23:45:22

标签: python-3.x networking async-await

我尝试使用subprocess.Popen进行异步ping过程,我试着理解在这种情况下我是如何实现它的

aList = []
async def sn(frm, to):
    i = 0
    for i in list(range(frm, to)):
        aList.append(i)

    cmd = "ping -n 1 " + '10.0.0.'
    coroutines = [subprocess.Popen(cmd + str(i), stdout=subprocess.PIPE) for i in aList]
    results = await asyncio.gather(*coroutines)
    print(results)

loop = asyncio.get_event_loop()
loop.run_until_complete(sn(frm, to))
loop.close()

2 个答案:

答案 0 :(得分:0)

class rscan(object):

    state = {'online': [], 'offline': []} # Dictionary with list
    ips = [] # Should be filled by function after taking range

    # Amount of pings at the time
    thread_count = 8

    # Lock object to prevent race conditions
    lock = threading.Lock()

    # Using Windows ping command
    def ping(self, ip):
        answer = subprocess.call(['ping','-n','1',ip],stdout = open('1.txt','w'))
        return answer == 0 and ip


    def pop_queue(self):
        ip = None

        self.lock.acquire() # lock !!!
        if self.ips:
            ip = self.ips.pop()

        self.lock.release()

        return ip


    def noqueue(self):
        while True:
            ip = self.pop_queue()

            if not ip:
                return None

            result = 'online' if self.ping(ip) else 'offline'
            self.state[result].append(ip) ### check again


    def start(self):
        threads = []

        for i in range(self.thread_count):

            t = threading.Thread(target=self.noqueue)
            t.start()
            threads.append(t)

        # Wait for all threads

        [ t.join() for t in threads ]

        return self.state

    def rng(self, frm, to, ip3):
        self.frm = frm
        self.to = to
        self.ip3 = ip3
        for i in range(frm, to):
            ip = ip3 + str(i)
            self.ips.append(ip)


if __name__== '__main__':
    scant = rscan()
    scant.thread_count = 8

编辑了一个我发现也使用线程代替Async& amp;等待

信用:http://blog.boa.nu/2012/10/python-threading-example-creating-pingerpy.html

答案 1 :(得分:0)

您可以找到更简单的代码,无需 async-await 即可 ping 主机。但如有必要,您可以尝试使用以下工作示例来 ping async-await

import platform
import subprocess

import aiohttp
import asyncio

async def getPingedHost(host, netTimeout=3):
  """ Description: Function to ping a host and get string of outcome or False
    Import: from shared.getPingedHost import getPingedHost
    Testing: python -m shared.getPingedHost
  """
  args = ['ping']

  platformOs = platform.system().lower()

  if platformOs == 'windows':
      args.extend(['-n', '1'])
      args.extend(['-w', str(netTimeout * 1000)])
  elif platformOs in ('linux', 'darwin'):
      args.extend(['-c', '1'])
      args.extend(['-W', str(netTimeout)])
  else:
      raise NotImplemented('Unsupported OS: {}'.format(platformOs))

  args.append(host)
  output = ''

  try:
    outputList = []
    if platformOs == 'windows':
      output = subprocess.run(args, check=True, universal_newlines=True, 
          stdout=subprocess.PIPE, # Capture standard out
          stderr=subprocess.STDOUT, # Capture standard error
        ).stdout

      outputList = str(output).split('\n')

      if output and 'TTL' not in output:
        output = False
    else:
        subprocess.run(args, check=True)

    output = outputList[2]
  except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
    output = False
  return output

async def main():
  async with aiohttp.ClientSession() as client:
    output = await getPingedHost('google.com')
    print(output)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())