Python 2.7 – Generate GET requests from web server

This script generates simple GET requests from a web server. Threading is used in order to generate multiple GET requests at the same time. Note that this script cannot create significant stress on a Web Server.

import requests
import threading


def get_thrasher():

    req_get  = requests.get('http://192.168.56.101/')

threads = []

for counter_1 in range(10):
    thrd = threading.Thread(target=get_thrasher())
    thrd.start()
    threads.append(thrd)

for counter_2 in threads:
    counter_2.join()
Share Button

Python: Check IPs for DNS entries and see if host is UP or DOWN. Export info to a CSV file

Checks IPs if they have a DNS entry. If they do it checks if the host is up. If an IP does not have a DNS entry it reports it. It does not report if an IP with out a DNS is down or not

import socket
import subprocess
import  netifaces
import csv
 
def checkPING(IP):
    try:
        ping = subprocess.check_output(['ping', '-c1', ip])
        return "Host is UP"
    except:
        return "Host is DOWN"
 
def checkDNS(IP):
    try:
        dns = socket.gethostbyaddr(ip)
        return dns[0]
    except:
        return "No DNS entry found"
 
 
ip_list = []
dns_list = []
status_list = []
 
csvfile= open('file.csv', 'w')
for loop_ip in range (62):
    ip = '10.0.0.%d' % loop_ip
    print ip, checkDNS(ip), checkPING(ip)
    #data = ip+" ",checkDNS(ip)+" ",checkPING(ip)
    #data_list.append(data)
    ip_list.append(ip)
    dns_list.append(checkDNS(ip))
    status_list.append(checkPING(ip))
writer = csv.writer(csvfile, dialect='excel')
writer.writerows(zip(ip_list, dns_list, status_list))
 
 
'''
#These lines will print each element of the list on a row
writer.writerow(ip_list)
writer.writerow(dns_list)
writer.writerow(status_list)
'''
 
'''
#Also possible threading implementation
for threads_1 in range(1):
    threads_ping.append(threading.Thread(target=executeCheck()))
    threads_ping[-1].start


for threads_2 in range(num_dns):
    threads_dns = append(threading.Thread(target=checkDNS))
    threads_dns.start()

for threads in threads_ping:
    threads.join()

for threads in threads_dns:
    threads.join()
'''
 
OUTPUT:
10.0.0.5 No DNS entry found Host is UP
10.0.0.6 No DNS entry found Host is DOWN
10.0.0.7 No DNS entry found Host is DOWN
Share Button

Python – Use threading to get all EOD quote prices from all NASDAQ symbols.

The script below goes to yahoo finance and takes the current price of all stocks from NASDAQ. There is really no real life application of this script. It was created to learn threading. The script obtains the prices for thousands of stocks with in a couple of seconds at most. The output at some sections is off due to the speed the results are being printed. In order for this to work you will have to download all the symbols for the NASDAQ exchange and save that info in a text file located in the same location the script is running from.

#!/usr/bin/python
import urllib
import re
import threading
from datetime import datetime

print "------------------------------------------"
print "Today's date: ", str(datetime.now())[0:10]
print "------------------------------------------"
print ""
print "Symbol    Price      Time"

def stock_prices_reader(smbl):
    url = "http://finance.yahoo.com/q?s=" + smbl + "&ql=0"
    #print url
    html_link = urllib.urlopen(url)
    html_read = html_link.read()
    regex = '(.+?)'
    pattern = re.compile(regex)
    price = re.findall(pattern, html_read)
    print (str(smbl).center(5)), (''.join(price).center(14)), str(datetime.now())[11:25]
    print (" ----".ljust(1)), ("-----".center(14)),("--------".rjust(5))

symbolsfile = open("symbols.txt")
symbolist = symbolsfile.read()
newsymbolist = symbolist.split(("\n"))

threadlist = []
for loop1 in newsymbolist:
    thrd = threading.Thread(target=stock_prices_reader, args=(loop1,))
    thrd.start()
    threadlist.append(thrd)

for loop2 in threadlist:
    loop2.join()

Share Button

Python – A simple Multithreaded Chat script.

There are two scripts that compose this chat script. The server and the client script. The server script is the one that uses the socket API and as a result follows the traditional steps of communication as dictated by the socket API. The client script connects to the chat server and communication between the two starts.

Note: The threads in this script are not closed. Also, the script is inefficient with the thread creation. As a result communication is limited to the amount of threads being created, which is hardcoded. This was my very first script using sockets and multithreading. It is a learning process. Continue reading

Share Button

Python – A simple example using threading module

Example 1: Threading example which loops 10 times by also creating threads for the function. This script however, does not ensure that threads are being closed.

import threading
import time

def somefunction():
    for loop in range (10):
        print "thread sleeps for 10 seconds"
        time.sleep(10)
        print "thread woke up"

for counter in range(10):
     threader = threading.Thread(target=somefunction)
     threader.start()

Example 2: The script below is the same as the one above. However it employs threading accounting by storing each thread to a list. This allows to close threads when the process exits.

import threading
import time

def somefunction():
    for loop in range (10):
        print "thread sleeps for 20 seconds"
        time.sleep(20)
        print "thread woke up"

threads = []
num_threads = 10
for i in range(num_threads):
     # here you need to pass in "somefunction" without parens
     threads.append(threading.Thread(target=somefunction))
     threads[-1].start()

# then you need to join them (join waits for threads to finish)
for thread in threads:
    thread.join()
Share Button