Exam Notes Section 4

Sockets in Python

  • Resolve IP to hostname
>>> import socket
>>> print(socket.gethostbyaddr("8.8.8.8"))
('google-public-dns-a.google.com', ['8.8.8.8.in-addr.arpa'], ['8.8.8.8'])
  • Resole hostname to IP
>>> import socket
>>> print(socket.gethostbyname("www.colorado.edu"))
128.138.129.98
  • Get protocol name with port number
>>> import socket
>>> print(socket.getservbyport(53))
domain
  • Get port number with protocol name
>>> import socket
>>> print(socket.getservbyname("https"))
443
  • UDP socket send data

socket.sendto(data,(ip_address,port_number))

  • UDP receive data

socket.recvfrom(size_buffer)

Hashing in Python

haslib provides various hashing mechanisms.

Example.

import hashlib
hash = hashlib.sha265() // specify the hashing algorithm
hash.update("some text or data to be hashed")
print(hash.hexdigest())  // returns the hash value in hex

Intro to Flask

  • Initialize Flask class

app = Flask(__name__)

  • URL –> Function
@app.route('/')
def index():
    do something

Handling Variables

  • URL –> Function (accept INT variable in url)
@app.route('/accept/<int:n>')
def accept(n):
    do something with n
  • URL –> Function (accept STRING variable in url)
@app.route('/accept/<string:n>')
def accept(n):
    do something with n
  • URL –> Function (accept MESSAGE variable in url)
@app.route('/accept/<msg:n>')
def accept(n):
    do something with n
  • URL –> Function (Accept GET,POST)
@app.route('/accept/,methods=['GET','POST'])
def accept():
    if request.method == 'POST':
        value=request.form['somevar']
        do something
@app.route('/accept/,methods=['GET','POST'])
def accept():
    username=request.args.get('username')  // returns username variable in GET

Logging in python

logging module provides capabilities for logging messages in application

logging.baseconfig(filename="/var/log/someprogram.log",level=logging.DEBUG)
logging.debug("App has started")

Ploting graphs in python

matplotlib module is used to plot line, bar and pie graphs in python

  • Plot a line graph
import matplotlib.pyplot as plt

x=[1,2,10,6,7,9]
plt.plot(x)
plt.xlabel("Other numbers")
plt.ylabel("Numbers")

plt.title("My number graphs")

plt.show()
  • Plot multiple line in a graph
import matplotlib.pyplot as plt

x=[1,2,10,6,7,9]
plt.plot(x)

x2=[10,4,5,3,2]
plt.plot(x2)

plt.xlabel("Other numbers")
plt.ylabel("Numbers")

plt.title("My number graphs")

plt.margins(0.0.25)  // specify margin at the begining on graph

plt.legend(["graph1","graph2"], loc="upper left")  // print a legent at upper left of graph

plt.savefig('test.jpg') // saves the graph as image, should be before show !

plt.show()

  • Plot a bar graph
import matplotlib.pyplot as plt
import numpy as np

y=[4,9,2,7,1]
groups=len(y)
index=np.arange(groups)

barwidth=0.5  // width of each bar

plt.bar(index,y,barwidth,color='r')

plt.xlabel("X label")
plt.ylabel("Y label")
plt.title("My first bar graph")
plt.xticks(index+barwidth,("A","B","C","D","E"))   // bar names

plt.show()   // show the graph

Reading a CSV File

csv module is used to create and write csv files in python

  • Reading a csv file
import csv

with open('test.csv') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        if row:
            do something
            // row[0] gives the first column data

Pretty tables in python

prettytable module is used to print tables in terminal.

from prettytable import PrettyTable

table = PrettyTable(["column1","column2"])  // define the header of the table

table.add_row([1,2])

print(table) // print the table to terminal

Run system commands from python

subprocess module is used to run system commands and get output to python program.

import subprocess

output = subprocess.check_output(["ping","-c","10","{}".format("8.8.8.8")])   // every argument should be a new list element

BeautifulSoup – easy web page scrapping

bs4 module is used to easily scrape a web page.
requests module is used to get, send data to/from a web page.

  • Get title from a page
from bs4 import BeautifulSoup
import requests

url="http://40.80.160.187"

r = requests.get(url)

soup=BeautifullSoup(r.text,"html.parser")

print(soup.title)
print(soup.title.string)
  • Get all links from a web page
from bs4 import BeautifulSoup

url="http://40.80.160.187"

r = requests.get(url)

soup=BeautifullSoup(r.text,"html.parser")

for a in soup.find_all('a',href=True):
    print(a)

Send a mail from python

smtplib module is used to send email from python script

import smtplib
from email.mime.text import MIMEText

msg=MIMEText("Some message")
msg['Subject'] = "This is the subject"
msg['From'] = mailfrom
msg['To'] = mailto

s = smtplib(mailserver,timeout=25)
s.sendmail(mailfrom,mailto,msg.as_string())