Python
Last updated
Was this helpful?
Last updated
Was this helpful?
touch python101.py
chmod u+x python101.py
nano python101.py
#!/usr/bin/env python3
python3 python101.py
#Print String
print("Strings and things:")
print('Hello, world!')
print("""Hello, this is
a multiline string :)""")
print("This is"+" a string")
print ('\n') #new line
print(50 + 50) #add --> 100
print(50 - 50) #substract --> 0
print(50 * 50) #multiply --> 2500
print(50 / 50) #divide --> 1.0
print(50 ** 2) #exponents --> 2500
print(50 % 6) #modulo --> 2
print(50 // 6) #number without leftovers --> 8
numb = -5
print(abs(numb)) # 5
print(pow(3,2)) # 3 square 2 = 9
print(max(5,8)) # highest number : 8
print(min(5,8)) # smallest number : 5
print(round(4.2)) # 4
print(round(4.7)) #5
--------------------------------
from math import *
print(floor(4.2)) #print 4
print(ceil(4.2)) #print 5
print(sqrt(36)) #print 6
quote = “All is fair in love and war”
print(len(quote)) #length
print(quote.upper()) #uppercase --> ALL IS FAIR IN LOVE AND VAR
print(quote.lower()) #lowercase --> all is fair in love and var
print(quote.title()) #title --> All Is Fair In Love And Var
print(quote.isupper()) #return false
print(quote.upper().isupper()) #return true
print(quote.index("is")) #4 (start index to 0)
name = “Protyro”
age = 23 #int
demi = 0.5 #float
print(int(age))
print(int(27.6)) # don't work
print("My name is " + name + " and I am " + str(age) + " years old.")
age += 1
print(age) ← 24 (23+1)
birthday = 1
age += birthday
print(age) ← 25 (23+1+1)
name = input("Please enter your name : ") # input type is string by default for py3
age = input("Please enter your age : ")
print("Hello " + name + " !")
print("You are " + age + " years old.")
#Functions
print ("Here is an example function")
def who_am_i(): #this is a function
name = "Protyro"
age = 23
print("My name is " + name + " and I am " + str(age) + " years old.")
who_am_i()
#adding parameters
def add_one_hundred(number):
print(number + 100)
add_one_hundred(100)
#multiple parameters
def add(x,y):
print(x + y)
add(7,7)
def multiply(x,y):
return x * y
print(multiply(8,9))
def square_root(x):
print(x ** .5)
square_root(64)
def nl():
print('\n')
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))
#Relational & 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 because 5 is not greater than 7
test_or = (7 > 5) or (5 < 7) #True
test_or2 = (7 > 5) or (5 > 7) #True
test_not = not True #False
def drink(money):
if money >= 2:
return "You've got yourself a drink"
else:
return "No drink 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 - Have brackets []
movies = ["Interstellar", "Inception", "Avengers", "Joker"]
print(movies[1]) #return the second item
print(movies[0]) #return first item of the list
print(movies[1:3]) #range start with 1 and end before 3 (2)
print(movies[1:]) # print all the list and start with item 1
print(movies[:1]) # start with item 0 and end at item 1
print(movies[-1]) # grab the last item
print(len(movies)) #print the numbers item
movies.append("Tu ne tueras point") # add a film to the list
print(movies)
movies.pop() #remove the last item
print(movies)
movies.pop(0) #remove the first item
print(movies)
movies.sort()
movies.reverse()
numbers = [1, 2, 3, 4, 6]
numbers.insert(4,5) # add number 5 after the 4
movies.extend(numbers)
print(movies) # numbers were added to movies list
moviesAndNumbers = movies.copy()
movies.clear()
#Tuples - Do not change, ()
grades = ("a","b","c","d","e","f")
print(grades[1]) # print b
#Looping
# For loops - start to finish an iterate
vegetables = ["cucumber","spinach","cabbage"]
for x in vegetables:
print(x)
for i in range(1,10): # First parameter is the start point and the second is the end point
print(i)
for i in range(0,20,2): # The third parameter tell the program how much to increment
print(i)
else :
print("Finish") #We can add an else statement at the end
# While loops - Execute as long as true
i = 1
while i < 10:
print(i)
i += 1
while True:
print("spam")
import sys # sys is system functions and parameters
from datetime import datetime as dt # import with alias
print(sys.version)
print(dt.now())
# Advanced Strings
my_name = "Protyro"
print(my_name[0]) #P
print(my_name[-1])#o
sentence = "This is a sentence."
print(sentence[:4]) # Print "This"
print(sentence[-4:]) # Print nce.
print(sentence.split()) # Split at each space
print(type(sentence.split())) # This is a list
print(sentence.replace("sentence","quote")
sentence_split = sentence.split()
sentence_join = ' '.join(sentence_split)
print(sentence_join)
quote = "He said, 'give me all your money'"
quote2 = "He said, \"give me all your money\""
print(quote)
print(quote2)
too_much_space = " hello "
print(too_much_space.strip()) #remove space
print("a" in "Apple")
print("A" in "Apple")
nl()
letter = "A"
word = "Apple"
print(letter.lower() in word.lower()) # Search "a" in "apple" and return true
movie = "Interstellar"
print("My favorite movie is {}.".format(movie))
# Dictionaries - Key/value pairs {}
drinks = {"Ice tea": 3, "Coca": 4, "Fanta": 2} # Drink is the key, price is the value
print(drinks)
employees = {"Finance": ["Bob", "Linda", "Tina"], "IT":["Alex", "Julien", "Seb"], "HR": ["Barbara", "Alice", "Julianne"]}
print(employees)
employees['Legal'] = ["Franck"] #add new key:value pair
print(employees)
employees.update({"Sales": ["Kevin", "Romain"]}) #add new key:value pair
print(employees)
drinks['Coca'] = 5
print(drinks)
print(drinks.get("Coca")) # Return the value (the price here)
#Sockets
import socket
HOST = '127.0.0.1'
PORT = 7777
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #AF_NET is ipv4 & SOCK_STREAM is the port
s.connect((HOST,PORT))
file = open("/path/file.txt","r")
print(file.read(5)) #print 5 caracters
print(file.readlines()) #print each line
print(file.readline()) #print a single line, can be invoked multiple times
for line in file:
print(line, end='')
#File mode :
#r -read / w -write /a -append / r+ -read and write
#There is more file modes not listed here
#-----------------------
file = open("test.txt","w")
file.write("This is a test") #overwrite
sudo apt install virtualenv
virtualenv --python=python3 EnvironmentName
source EnvironmentName/bin/activate
deactivate
sudo apt install python3-pip
pip3 install pwntools
pip3 install -r requirements.txt
-----------------------
from pwn import *
#!/bin/python3
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(1,100): #(1,65535)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((target, port)) # Return 0 if port is open, 1 otherwise
#print("Checking port {}...".format(port))
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("Could connect to ip address.")
sys.exit()