mkdir~/tcm/peh/pythonnanofirst.py# or with Sublime, VsCode installedsublfirst.pycodefirst.py
Example of Python script
#!/bin/python3 - first line
Use # for comments
#!/bin/python3# Print string <--- this is a commentprint("Hello, world!")
# eventually make the script runnablechmod+xfirst.py# it must containg "#!/bin/python3" as first line, to run it with./first.py# Or run it with python3python3first.py
#!/bin/python3# Print stringprint("Hello, World!")# Single quotesprint('Hello, World!')# Double quotesprint("""Multiple linesstring!""")# Triple quotes = Multiple linesprint("Hello "+"World!")# Concatenate stringsprint("First line.\nSecond line.")# New lineprint('This isn\'t a long string.')# \' to escape the single quote..or use double quotes# Creationmy_string ="Hello, World!"# Accessing individual characters by indexingprint(my_string[0])# output = 'H'# Concatenationgreeting ='Hello'+' '+'World!'# Length of the stringprint(len(my_string))# Slicing# Extract a substring from a string using slicing, specifying the start and end indices.substring = my_string[7:12]print(substring)# output = 'World'# Methods to manipulate and transform stringsprint(my_string.upper())# output = 'HELLO, WORLD!'
#!/bin/python3import math # Module with various math functions and constants# Operatorsprint(10+10)# Additionprint(10-10)# Subtractionprint(10*10)# Multiplicationprint(25/10)# Division with remainder - floatprint(25//10)# No remainder division - returns the quotient as an integerprint(25%10)# Modulo - returns the remainder of divisionprint(10**5)# Exponentiation# Using math functionsprint(math.sqrt(500))# Square rootprint(math.pow(2, 10))# Raise a to power of bprint(math.sin(math.pi/2))# Calculate sine of pi/2 (in radians)
➡️ A variable is a dynamic container for storing data values.
➡️ A method (or function) is a block of code which runs when called and performs specific operations. It can have return values, perform actions, accept parameters, etc.
nanovars.py
#!/bin/python3# Variables assignment with different data typesage =22# integerheight =69.5# floatname ="Sys"# stringis_true =True# boolean# Variable usageprint(int(age))print(int(22.7))print("Hello, "+ name +". Is your height "+str(height) +" cm?")age +=1# Add 1 to age variableprint(age)if is_true:print("The condition is true \n")# is_true boolean is "True"# Built-in methodquote ="The quieter you become, the more you can hear."print(quote.upper())# upper-case methodprint(quote.lower())# lower-case methodprint(quote.title())# title-case methodlength =len(quote)# Count charactersprint("Quote length:", length)print('\n')
➡️ A function is a reusable block of code that performs a specific task.
defined with the def keyword
def function_name():
accepts parameters
❗ Indentation is very important in Python, since it's used to indicate a block of code.
nanofunc.py
#!/bin/python3# Function with parametersdefgreet(name):print("Hello, "+ name +"!")# Function call with an argument that is assigned to the "name" paramgreet("Sys")age =22# Function without parametersdefwho_am_i(): name ="Sys"# Local variable age =55# Local variableprint("My name is "+ name +" and I am "+str(age) +" years old.\n")who_am_i()print(age)# Not the function's "age" variable# Parametersprint('Add 100:')defadd_one_hundred(num):print(num +100)add_one_hundred(400)# Call function with an argumentprint('Add 2 numbers:')defadd(x,y):print(x + y)add(400,300)print('Multiply 2 numbers:')# Return statementdefmultiply(x,y):return x * y multiply(5,5)# Can be assigned to a variable or calledprint(multiply(5,5))result =multiply(9,9)print(result)print('Square root:')defsquare_root(x):print(x **.5)square_root(64)print('This is a new line:')# New line functiondefnl():print('\n')nl()
➡️ Boolean expressions are expressions that evaluate to either True or False, used in conditional statements and logical operations.
➡️ Relational operators are used to compare values and create boolean expressions.
nanooper.py
#!/bin/python3# Boolean expressionsprint("Boolean expressions:")bool1 =Truebool2 =2*3==6# == Check if two values are equalbool3 =Falsebool4 =3*3!=9# != Check if two values are not equalprint(bool1,bool2,bool3,bool4)# Output: True, True, False, Falseprint(type(bool1))# Outputs the class 'bool'bool5 ="True"print(type(bool5))# Outputs the class 'str'# Relational and Boolean operatorsprint('\n')print("Relational and Boolean operators:")greater_than =7>5# greater_than = Trueless_than =5<7# less_than = Truegreater_than_equal_to =7>=7less_than_equal_to =7<=7# All above statements are truetest_and =TrueandTrue#Truetest_and2 =TrueandFalse#Falsetest_or =TrueorTrue#Truetest_or2 =TrueorFalse#Truetest_not =notTrue#False# Relational operators - Compare valuesx =5y =10print("x =",x)print("y =",y)print("x == y")print("",x == y)# Output: Falseprint("x < y")print("",x < y)# Output: True# Boolean expressions and Logical operatorsprint('\n')print("Boolean expressions:")print("x < y and y > 0")print("",x < y and y >0)# Output: True - if both operands are Trueprint("x < y or y < 0")print("",x < y or y <0)# Output: True - if at least one operand is Trueprint("not (x == y)")print("",not (x == y))# Output: True - negates the value of the operand
➡️ Conditional statements allow the execution of different actions based on certain conditions. Logical math conditions can be used in if statements and loops.
nanoconditions.py
#!/bin/python3# Conditional Statementsdeficecream(money):ifmoney>=3:return"Enjoy yourself an icecream!" else:return"No icecream for you!"print(icecream(5)) # 5$ > 3 - if statement is trueprint(icecream(1)) # 1$ < 3 - if statement is falseprint('\n')# Multiple conditionsdefalcohol(age,money):# Function with multiple parametersif (age>=18) and (money >=5): # Conditional statement, relational operators (boolean)return"You're getting a Pina Colada!!!"elif (age>=18) and (money <5):return"You need more money for a drink."elif (age<18) and (money >=5):return"You are too young kid!" else:return"Hey kid, you don't have money nor the age for an alcoholic drink."print(" Age+Money ok:")print(alcohol(18,5))print(" Age ok, but no Money:")print(alcohol(18,4))print(" Money ok, but no Age:")print(alcohol(16,6))print(" No Age, No Money:")print(alcohol(17,3))print('\n')print('IF-ELSE')# "if - else" Statementx=5ifx>0:print("x is positive") # Executed if x > 0 is TRUEelse:print("x is not positive") # Executed if x > 0 is FALSEprint('IF-ELIF-ELSE')# Multiple Conditions "if - elif - else" Statement x=0ifx>0:print("x is positive") # Executed if x > 0 is TRUEelifx<0:print("x is negative") # Executed if x > 0 is FALSE and x < 0 is TRUEelse:print("x is zero") # Executed if both conditions are FALSE
➡️ Lists are used to store multiple items in a single variable.
list = ["item1", "item2", "item3"]
items are ordered, changeable and indexed (first item index starts at [0])
nanolists.py
#!/bin/python3# LISTSprint("LISTS")fruits = ["apple","banana","orange"]# Mutable Listsfruits[1]="grape"# Modifying an elementfruits.append("kiwi")# Adding an element to the endfruits.remove("apple")# Removing an elementprint(fruits)print('\n')# List Operationsfruits = ["apple","banana","orange"]fruits2 = ["grape","kiwi"]print("Fruits: ",fruits)print("Fruits2: ",fruits2)combined = fruits + fruits2 # Concatenationprint("Combined: ",combined)# Output: ["apple", "banana", "orange", "grape", "kiwi"]# Lengthprint("Fruits list length is:",len(fruits))# Output: 3 (elements in a list)# Slicingsublist = fruits[1:3]print("Sublist: ",sublist)# Output: ["banana", "orange"]# List Iterationprint('\n')print("Fruits list content by iteration:")for fruit in fruits:print(fruit)# Output: "apple", "banana", "orange"# MOVIESprint('\n')print("MOVIES")movies = ["Kickboxer","The Grandmaster","Ip Man","Rocky","Ong Bak","Rurouni Kenshin Origins"]print("Movies list is: ",movies)print(movies[1])# Returns the second itemprint(movies[0])# Returns the first itemprint(movies[1:3])# Returns 2 items starting from index 1print(movies[1:])# Returns all items starting from index 1 to end of listprint(movies[:3])# Returns everything before index 3print(movies[-1])# Returns last itemprint("Movies list length is:",len(movies))movies.append("The Raid 2")print(movies)movies.insert(2,"Enter The Dragon")print(movies)movies.pop()# Remove the last itemprint(movies)movies.pop(0)# Remove the first itemprint(movies)new_movies = ["Creed III","John Wick"]all_movies = movies + new_moviesprint("All movies list:",all_movies)# Two dimentional listsprint('\n')print("GRADES")grades = [["Ron",55], ["Harry",66], ["Luna",87]]rons_grade = grades[0][1]print(rons_grade)grades[0][1] =76print(grades)
➡️ Looping allows to repeat a block of code multiple times, iterating over a sequence and performing repetitive tasks.
for loop: iterate over a sequence and execute a set of statements for each item in a list, tuple, string, set, dictionary
while loop: execute a set of statements as long as a condition is true
nanoloops.py
#!/bin/python3# Looping# "for" loops - start to finish of an iterateprint("FOR Loop:")fruits = ["apple","banana","cherry"]for fruit in fruits:# iterate over each item in "fruits" listprint(fruit)# "while" loops - execute as long as true, until falseprint("\nWHILE Loop:")count =0while count <10:# as long as true, code will be executedprint(count) count +=1# "break" statement - stop the loop prematurelyprint("\nBrake:")fruits = ["apple","banana","cherry"]for x in fruits:if x =="banana":breakprint(x)# "continue" statement - skip current iteration and move to the next oneprint("\nContinue:")fruits = ["apple","banana","peach"]for y in fruits:if y =="banana":continueprint(y)
#!/bin/python3# Advanced Stringsmy_name ="sysElement"# this string is immutableprint(my_name[0])# first letterprint(my_name[-1])# last lettersentence ="The quieter you become, the more you can hear."print("Sentence:\n",sentence)print(sentence[:3])# Print everything before the index 3print("Sentence split:\n",sentence.split())# Delimiter - default is a "space"sentence_split = sentence.split()sentence_join =' '.join(sentence_split)print("Sentence join:\n",sentence_join)# Character escaping with \quote ='The master said: "The quieter you become, the more you can hear."'print(quote)quote ="The master said: \"The quieter you become, the more you can hear.\""print(quote)# Striptoo_much_space =" master "print(too_much_space.strip(),"\n")# Default delimiter is "space"# Case insensitiveprint("A"in"Apple")# TRUEprint("a"in"Apple")# FALSEletter ="A"word ="Apple"print(letter.lower() in word.lower())# TRUE# String Formattingname ='Alice'age =30print("My name is %s and I'm %d years old."% (name, age))# Output: My name is Alice and I'm 30 years old.movie ="Minions"print("My favorite movie is {}.".format(movie))# String format methodprint("My favorite movie is %s."% movie)# % formattingprint(f"My favorite movie is {movie}.")# string literal
#!/bin/python3# Dictionaries - key/value pairs {}# Creation and access# The values can be of any data typeemployees ={"Finance": ["Bob","Linda","Tina"],"IT": ["Gene","Alex","Louise"],"HR": ["Jimmy","John"]}print(employees)# Modificationemployees['Legal']= ["Mr.Tex"] # Add new key:value pairprint(employees)employees.update({"Sales": ["Andie", "Ollie"]})# Add new key:value pairprint(employees)del employees["HR"]# Delete a key:value pairprint(employees,"\n")cocktails ={"Mojito":6,"Long Island":9,"Lemon Drop":8}# drink is key, price is valueprint("Cocktails Dictionary:\n",cocktails)print("Mojito price is:",cocktails["Mojito"],"\n")# Update a valuecocktails['Long Island']=10print(cocktails)print("Long Island price is:",cocktails.get("Long Island"),"\n")# Iterationprint("Cocktails Dictionary Lenght is:",len(cocktails))print("\nCocktails Dictionary contains:")for key in cocktails:print(key, cocktails[key])
➡️ Modules are like code libraries, containing a set of functions to include in the application.
reside in external Python files/libraries
import <module>
nanomodules.py
#!/bin/python3# Modules Importing#import math # Import module#result = math.sqrt(25)#print(result)from math import sqrt # Import specific functions or variablesresult =sqrt(25)# Use function without prefixing module nameprint(result)import math as m # Import module as an aliasresult = m.sqrt(25)print(result)from math import*# Import all functions and variablesresult =sqrt(25)# Use functions without prefixing module nameprint(result)import sys # System functions and parametersfrom datetime import datetime as dt # Import with alias print(sys.version)print(dt.now())
➡️ Sockets are used to send messages across a network, enabling programs to establish connections, send and receive data over various network protocols.
Primary socket module methods and functions are:
socket()
.bind()
.listen()
.accept()
.connect()
.connect_ex()
.send()
.recv()
.close()
nanos.py
#!/bin/python3import socket### e.g. 1 - TCP SERVER# Create a TCP sockettcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# AF_INET is for IPv4 - Address family# SOCK_STREAM is for the TCP port - Socket type# Create a UDP socketudp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)# SOCK_DGRAM is for UDP port# Bind the socket to a specific address and portserver_address = ('localhost',1234) # localhost = 127.0.0.1tcp_socket.bind(server_address)# Listen for incoming connectionstcp_socket.listen(5)# 5 is the "backlog" parameter# "backlog" = number of unaccepted connections that the system will allow before refusing new connectionswhileTrue:# Accept a client connection client_socket, client_address = tcp_socket.accept()# Return value is a pair (conn, address)# Receive and send data data = client_socket.recv(1024)# Read data sent by client - 1024 = max buffer size client_socket.send(b"Received: "+ data)# Return the number of bytes sent# Close the client socket client_socket.close()
nanos2.py
#!/bin/python3import socket### e.g. 2 - Connect to a portHOST ='127.0.0.1'# localhost loopback addressPORT =5555s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST,PORT))
Listen to the 5555 port with nc and launch the s2.py Python script.
the socket will connect to the listening port
nc-nvlp5555
e.g. Port scanner
Port scanning of an IP address
This port scanner is a proof-of-concept not optimized script, that checks for open ports on a specified target IP within a given range.
nanoscanner.py
#!/bin/python3import sysimport socketfrom datetime import datetime# Define targetiflen(sys.argv)==2: target = socket.gethostbyname(sys.argv[1])#Translate hostname to IPv4else:print("Invalid amount of arguments.")print("Syntax: python3 scanner.py <ip>")#Add a pretty bannerprint("-"*50)print("Scanning target "+target)print("Time started: "+str(datetime.now()))print("-"*50)try:for port inrange(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 port is open it throws a 0, otherwise 1if result ==0:print("Port {} is open".format(port)) s.close()exceptKeyboardInterrupt:print("\nExiting program.") sys.exit()except socket.gaierror:print("Hostname could not be resolved.") sys.exit()except socket.error:print("Could not connect to server.") sys.exit()
(ChatGPT) Enhanced script
#!/bin/python3import sysimport socketfrom datetime import datetimedefprint_banner(target):# Prints a banner with the target information and current time.print("-"*50)print(f"Scanning target {target}")print(f"Time started: {datetime.now()}")print("-"*50)defvalidate_arguments(args):# Validates the number of arguments and returns the target address.iflen(args)!=2:print("Invalid number of arguments.")print("Syntax: python3 scanner.py <ip>") sys.exit(1)return args[1]defscan_ports(target,start_port=50,end_port=85):# Scans the ports in the given range on the target IP address.try:for port inrange(start_port, end_port +1):with socket.socket(socket.AF_INET, socket.SOCK_STREAM)as s: socket.setdefaulttimeout(1) result = s.connect_ex((target, port))# Returns 0 if port is open, otherwise 1if result ==0:print(f"Port {port} is open")exceptKeyboardInterrupt:# Handles user interrupt (Ctrl+C)print("\nExiting program.") sys.exit(0)except socket.gaierror:# Handles errors related to resolving the hostnameprint("Hostname could not be resolved.") sys.exit(1)except socket.error:# Handles general socket errorsprint("Could not connect to server.") sys.exit(1)defmain():# Main function to drive the script. target =validate_arguments(sys.argv) target_ip = socket.gethostbyname(target)# Translate hostname to IPv4print_banner(target_ip)scan_ports(target_ip)if__name__=="__main__":main()
➡️ input() function is used to take input from the user via the console and return it as a string (by default). Proper validation and error handling is necessary for specific data types and invalid inputs.
nanoinput.py
#!/bin/python3# Inputname =input("Enter your name: ")# Promptprint("Hello, "+ name +"!")# Print using the entered nameage =input("Enter your age: ")age =int(age)# Convert the input string to an integerprint("You will be "+str(age+1) +" next year.")# Calculatorx =float(input("Give me a number: "))o =input("Give me an operator: ")y =float(input("Give me yet another number: "))if o =="+":print(x + y)elif o =="-":print(x - y)elif o =="/":print(x / y)elif o =="*":print(x * y)elif o =="**"or0=="^":print(x ** y)else:print("Unknown operator.")
➡️ To read from a file, open it in read mode using open("filename", "r"). Then, use read(), readline(), or readlines() to access its contents.
➡️ To write to a file, open it in write mode using open("filename", "w"). Then, use the write() method to add content to the file.
➡️ To append content to an existing file, open it in append mode using open("filename", "a"). Then, use the write() method to add content.
nanoreadwrite.py
#!/bin/python3# READ# Open the file in read modemonths =open('months.txt', "r")# Read the entire contentcontent = months.read()print(content)# Read a single lineline = months.readline()print(line)# Read all lineslines = months.readlines()print(lines)# Close the filemonths.close()# Alternative way to properly close the file even if exception occurswithopen('months.txt', "r")as months: content = months.read()print(content)# WRITE# Open the file in write modedays =open("days.txt", "w")# Write content to the file