Introduction to Python – Practical Ethical Hacking by TCM

by Kal Bartal
#!/bin/python3

Declares that this is a python script

To run the script:

python3 first.py

or

./first.py

Strings

#!/bin/python3

#Print string
print("Hello, world!")#double quotes
print('\n')#new line 
print('Hello, world!')#single quotes 

print("""This string runs
multiple lines!""")#triple quotes for multi-line

print("This string is "+"awesome!")#we can also concatenete

Math

#Math
print(50 + 50) #add
print(50 - 50) #subtract
print(50 * 50) #multiply
print(50 / 50) #divide
print(50 + 50 - 50 * 50 / 50)#PEMDAS
print(50 ** 50) #exponents
print(50 % 6) #modulo
print(50 / 6)
print(50 // 6) #no leftovers

Variables & Methods

A variable is a placeholder.
Methods are functions that are available for a given object.

#Variables and Methods
quote = "All is fair in love and war."
print(quote.upper()) #uppercase
print(quote.lower()) #lowercase
print(quote.title()) #titlecase

print(len(quote))

name = "Heath" #string
age = 30 #int int(30)
gpa = 3.7 #float float(3.7)

print(int(age))
print(int(30.1))

print("My name is " + name + " and I am " + str(age) + " years old.")

age += 1
print(age)

birthday = 1
age += birthday
print(age)

Functions

Functions are organised blocks of codes or ‘mini programs’.

print('\n')
#Functions
print("Here is an example function:")

def who_am_i(): #this is a function
    name = "Heath"
    age = "30"
    print("My name is " + name + " and I am " + str(age)    + " years old.")

who_am_i()

#Adding parameters
def add_one_hundred(num):
    print(num + 100)

add_one_hundred(100)

#Multiple parameters
def add(x,y):
    print(x + y)

print(7,7)

def multiply(x,y):
    return x * y

print(multiply(7,7))

def square_root(x):
    print(x ** .5)

square_root(64)

def nl():
    print('\n')

nl()

Boolean Expressions

Useful resource: https://ryanstutorials.net/boolean-algebra-tutorial/

nl()
#Boolean expressions (True or False)
print("Boolean expressions:")

bool1 = True
bool2 = 3*3 == 9
bool3 = False
bool4 = 3*3 !=9

print(bool1,bool2,bool3,bool4)
print(type(bool1))

bool5 = "True"
print(type(bool5))

Relational and Boolean Operators

nl()
#Relational and Boolean Operators
greater_than = 7 > 5
less_than = 5 < 7
greater_than_equal_to = 7 >= 7
less_than_equal_to = 7 <= 7

test_and = (7 > 5) and (5 < 7) #True
test_and2 = (7 > 5 ) and (5 > 7) #False
test_or = (7 > 5) or (5 < 7) #True
test_or2 = (7 > 5) or (5 > 7) #True

test_not = not True #False

Conditional Statements

nl()
#Conditional Statements
def drink(money):
    if money >= 2:
        return "You've got yourself a drink"
    else: 
        return "No drinl for you!"

print(drink(3))
print(drink(1))

def alcohol(age,money):
    if (age >= 21) and (money >=5):
        return "We're getting a drink!"
    elif (age >= 21) and (money < 5):
        return "Come back with more money!"
    elif (age < 21) and (money >= 5):
        return "Nice try, kid!"
    else: 
        return "You're too poor and too young!"

print(alcohol(21,5))
print(alcohol(21,4))
print(alcohol(20,4))

Lists

Lists are data structures. They have brackets.

nl()
#Lists - Have brackets []
movies = ["When Harry Met Sally", "The Hangover", "The Perks of Being a Wallflower", "The Exorcist"]

print(movies[1]) #returns the second item
print(movies[0]) #returns the first item in the list
print(movies[1:4]) 
print(movies[1:])
print(movies[:1])
print(moves[-1])

print(len(movies))
movies.append("JAWS")
print(movies)

movies.pop()
print(movies)

movies.pop(0)
print(movies)

Tuples

Tuples are like lists but they are immutable. they cannot be changed.

nl()
#Tubles - Do not change ()
grades = ("a", "b", "c,", "d", "f")
print(grades[1])

Looping

nl()
#Looping

#For loops - start to finish of an iterate
vegetables = ["cucumber", "spinach", "cabbage"]
for x in vegetables:
    print(x)

#While loops - Execute as long as true
i = 1
while i < 10:
    print(i)
    i += 1

Importing Modules

#!/bin/python3
import sys #system funsctions and parameters
from datetime import datetime as dt #import with alias

print(sys.version)
print(dt.now())

Advanced Strings

m_name = "Heath"
print(my_name[0])
print(my_name[-1])

sentence = "This is a sentence."
print(sentence[:4])

print(sentence.split())

sentence_split = sentence.split()
sentence_join = ' '.join(sentence_split)
print(sentence_join)

quote = "He said, \"give me all your money\""
print(quote)

too_much_space = "          Hello         "
print(too_much_space.strip())

print("a" in "Apple")

letter = "A"
word = "Apple"
print(letter.lower() in word.lower()) #Improved

movie = "The Hangover"
print("My favourite movie is {}.".format(movie))

Dictionaries

#Dictionaries - key/value pairs {}
drinks = {"White Russian": 7, "Old Fashion": 10, "Lemon Drop": 8} #drink is key, price is value
print(drinks)

employees = {"Finance": ["Bob", "Linda", "Tina"], "IT": ["Gene", "Louise", "Teddy"], "HR": ["Jimmy Jr.", "Mort"]}
print(employees)

employees['Legal'] = ["Mr.Frond"] #add new key:value pair
print(employees)
employees.update({"Sales": ["Andie", "Ollie"]})
print(employees)

drinks['White Russian'] = 8
print(drinks)

print(drinks.get("White Russian"))

Sockets

Sockets are used for connecting an IP address to an open port. (Connecting one node to another)

#!/bin/python3

import socket

HOST = '127.0.0.1'
PORT = 7777

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))

Tool Building

#!/bin/python

import sys
import socket
from datetime import datetime

#Define our target
if len(sys.argv) == 2:
    target = socket.gethostbyname(sys.argv[1]) #Translate hostname to IPv4
else:
    print("Invalid amount of arguments.")
    print("Syntax: python3 scanner.py <ip>")
    
#Add a pretty banner
print("-" * 50)
print("Scanning target "+target)
print("Time started: "+str(datetime.now()))
print("-" * 50)

try:
    for port in range(50,85):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(1)
        result = s.connect_ex((target,port)) #returns an error indicator
        if result == 0:
                print("Port {} is open".format(port))
        s.close()
        
except KeyboardInterrupt:
    print("\nExiting program.")
    sys.exit()
    
except socket.gaierror:
    print("Hostname could not be resolved.")
    sys.exit()
    
except socket.error:
    print("Couldn't connect to server.")
    sys.exit()

Related Posts

Leave a Comment