Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python parallel subprocess commands while suppressing output

I am doing a simple ip scan using ping in python. I can run commands in parallel as demonstrated in this answer. However, I cannot suppress the output since it uses Popen, and I can't use check_output since the process returns with a exit status of 2 if a host is down at a certain ip address, which is the case for most addresses. Using a Pipe is also out of the question since too many processes are running concurrently.

Is there a way to run these child processes in python concurrently while suppressing output? Here is my code for reference:

def ICMP_scan(root_ip):
  host_list = []
  cmds = [('ping', '-c', '1', (root_ip + str(block))) for block in range(0,256)]
  try:
      res = [subprocess.Popen(cmd) for cmd in cmds]
      for p in res:
        p.wait()
  except Exception as e:
      print(e)
like image 539
Stuart Avatar asked May 20 '26 01:05

Stuart


1 Answers

How about piping the process output to /dev/null.

Basing on this answer:

import os

devnull = open(os.devnull, 'w')

subproc = subprocess.Popen(cmd, stdout=devnull, stderr=devnull)
like image 115
Phoenix Avatar answered May 22 '26 15:05

Phoenix