Python
August 16, 2019

Builtin webserver

To start a webserver run the command below:

1
python3 -m http.server 8080

Ping

Pinger1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python2.7
from threading import Thread
import subprocess
from Queue import Queue

num_threads = 4
queue = Queue()
ips = ["216.58.206.196"]
#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()

Pinger 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
## Format is : <Time> <Date> <PacketsSent> <PacketsRecieved> <PercentageLoss> <RTTStatistic>
import sys
import subprocess
import time
import re

def ping(count,target,outFilePath):
    date = time.strftime("%d-%m-%y")
    outFile = open(outFilePath+target+'-'+date,'a')
    start = time.strftime("%H-%M-%S %d-%m-%y")
    output = subprocess.check_output(["ping","-c",count,"-q",target])
    output = output.split('\n')
    result = start + " " + filterResult(output[3]) + " " + output[4] + "\n"
    outFile.write('%s' % result)
    outFile.close()

def run(interval,count,target,outFile):
    now = time.time()
    while True:
        ping(count,target,outFilePath)
        #print "ping burst over"
        while time.time() - now<interval:
            time.sleep(interval - (time.time() - now))
        now = time.time()


def filterResult(s):
    re1='(\\d+)'	# Integer Number 1
    re2='.*?'	# Non-greedy match on filler
    re3='(\\d+)'	# Integer Number 2

    rg = re.compile(re1+re2+re3,re.IGNORECASE|re.DOTALL)
    m = rg.search(s)
    if m:
        int1=int(m.group(1))
        int2=int(m.group(2))
        return ("%d %d %f" % (int1,int2,float(int1-int2)/float(int2)) )

    else:
            return "Error"

if __name__=="__main__":
    if len(sys.argv)<4:
        print "Usage : python pingScript.py interval(mins) count target [outFilePath]"
        exit(-1)
    if len(sys.argv) ==5:
        interval, count, target, outFilePath = sys.argv[1:]
        outFilePath +='-'
    else:
        interval, count, target = sys.argv[1:]
        outFilePath = ""
        
    run(int(interval)*60,count,target,outFilePath)