development:python:os_thread

Differences

This shows you the differences between two versions of the page.


development:python:os_thread [2019/10/31 09:05] (current) – created - external edit 127.0.0.1
Line 1: Line 1:
 +====== Python: Thread, for loop, script arguments, regex and OS execute ======
 +For loop 255 times, create a thread, execute a function and pass a system argument, execuring a system command and printing its output
  
 +<code python>
 +#!/usr/bin/python
 +
 +import threading
 +import time
 +import os
 +import sys 
 +import re
 +
 +def ppp(addr):
 +    response = os.system('ping -c 1 ' + str(addr) + ' | grep from | awk \'{print "ip=" substr($4,1,length($4)-1),$7}\'')
 +
 +if len(sys.argv) == 2:
 +    if str(sys.argv[1]).endswith('.'):
 +        ipbase=str(sys.argv[1])
 +    else:
 +        ipbase=str(sys.argv[1]) + '.'
 +
 +    pattern = re.compile("^(([0-9]{1,2})|([0-1]{1}[0-9]{2})|([2]{1}[0-4]{1}[0-9]{1})|([2]{1}[5]{1}[0-5]{1}))\.(([0-9]{1,2})|([0-1]{1}[0-9]{2})|([2]{1}[0-4]{1}[0-9]{1})|([2]{1}[5]{1}[0-5]{1}))\.(([0-9]{1,2})|([0-1]{1}[0-9]{2})|([2]{1}[0-4]{1}[0-9]{1})|([2]{1}[5]{1}[0-5]{1}))\.$")
 +    if pattern.match(ipbase):
 +        for addrs in range(1,255):
 +            x = threading.Thread(target=ppp, args=(ipbase + str(addrs), ))
 +            x.start()
 +    else:
 +        print('./ips 192.168.0.')
 +else:
 +    print('./ips 192.168.0.')
 +</code>