Basic Python
Tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al π¬ gruppo Discord o al gruppo telegram o seguici su Twitter π¦ @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
Python Basics
Informazioni utili
list(xrange()) == range() β> In python3 range Γ¨ lβxrange di python2 (non Γ¨ una lista ma un generatore)
La differenza tra una Tupla e una Lista Γ¨ che la posizione di un valore in una tupla le conferisce significato, mentre le liste sono solo valori ordinati. Le tuple hanno strutture ma le liste hanno un ordine.
Operazioni principali
Per elevare un numero si usa: 3**2 (non 3^2)
Se fai 2/3 restituisce 1 perchΓ© stai dividendo due int (interi). Se vuoi decimali dovresti dividere float (2.0/3.0).
i >= j
i <= j
i == j
i != j
a e b
a o b
non a
float(a)
int(a)
str(d)
ord(βAβ) = 65
chr(65) = βAβ
hex(100) = β0x64β
hex(100)[2:] = β64β
isinstance(1, int) = True
βa bβ.split(β β) = [βaβ, βbβ]
β β.join([βaβ, βbβ]) = βa bβ
βabcdefβ.startswith(βabβ) = True
βabcdefβ.contains(βabcβ) = True
βabc\nβ.strip() = βabcβ
βapbcβ.replace(βpβ,ββ) = βabcβ
dir(str) = Elenco di tutti i metodi disponibili
help(str) = Definizione della classe str
βaβ.upper() = βAβ
βAβ.lower() = βaβ
βabcβ.capitalize() = βAbcβ
sum([1,2,3]) = 6
sorted([1,43,5,3,21,4])
Unire caratteri
3 * βaβ = βaaaβ
βaβ + βbβ = βabβ
βaβ + str(3) = βa3β
[1,2,3]+[4,5]=[1,2,3,4,5]
Parti di una lista
βabcβ[0] = βaβ
βabcβ[-1] = βcβ
βabcβ[1:3] = βbcβ da [1] a [2]
βqwertyuiopβ[:-1] = βqwertyuioβ
Commenti
# Commento su una riga
βββ
Commento su piΓΉ righe
Un altro
βββ
Cicli
if a:
#somethig
elif b:
#something
else:
#something
while(a):
#comething
for i in range(0,100):
#something from 0 to 99
for letter in "hola":
#something with a letter in "hola"
Tuple
t1 = (1,β2,βthreeβ)
t2 = (5,6)
t3 = t1 + t2 = (1, β2β, βthreeβ, 5, 6)
(4,) = Singelton
d = () tupla vuota
d += (4,) β> Aggiunta in una tupla
CANT! β> t1[1] == βNuovo valoreβ
list(t2) = [5,6] β> Da tupla a lista
Lista (array)
d = [] vuota
a = [1,2,3]
b = [4,5]
a + b = [1,2,3,4,5]
b.append(6) = [4,5,6]
tuple(a) = (1,2,3) β> Da lista a tupla
Dizionario
d = {} vuoto
monthNumbers={1:βGenβ, 2: βfebβ,βfebβ:2}β> monthNumbers ->{1:βGenβ, 2: βfebβ,βfebβ:2}
monthNumbers[1] = βGenβ
monthNumbers[βfebβ] = 2
list(monthNumbers) = [1,2,βfebβ]
monthNumbers.values() = [βGenβ,βfebβ,2]
keys = [k for k in monthNumbers]
a={β9β:9}
monthNumbers.update(a) = {β9β:9, 1:βGenβ, 2: βfebβ,βfebβ:2}
mN = monthNumbers.copy() #Copia indipendente
monthNumbers.get(βkeyβ,0) #Controlla se la chiave esiste, Restituisce il valore di monthNumbers[βkeyβ] o 0 se non esiste
Insieme
Negli insiemi non ci sono ripetizioni
myset = set([βaβ, βbβ]) = {βaβ, βbβ}
myset.add(βcβ) = {βaβ, βbβ, βcβ}
myset.add(βaβ) = {βaβ, βbβ, βcβ} #Nessuna ripetizione
myset.update([1,2,3]) = set([βaβ, 1, 2, βbβ, βcβ, 3])
myset.discard(10) #Se presente, rimuovilo, altrimenti, nulla
myset.remove(10) #Se presente rimuovilo, altrimenti, solleva unβeccezione
myset2 = set([1, 2, 3, 4])
myset.union(myset2) #Valori in myset O myset2
myset.intersection(myset2) #Valori in myset E myset2
myset.difference(myset2) #Valori in myset ma non in myset2
myset.symmetric_difference(myset2) #Valori che non sono in myset E myset2 (non in entrambi)
myset.pop() #Ottieni il primo elemento dellβinsieme e rimuovilo
myset.intersection_update(myset2) #myset = Elementi in entrambi myset e myset2
myset.difference_update(myset2) #myset = Elementi in myset ma non in myset2
myset.symmetric_difference_update(myset2) #myset = Elementi che non sono in entrambi
Classi
Il metodo in __It__ sarΓ quello utilizzato da sort per confrontare se un oggetto di questa classe Γ¨ piΓΉ grande di un altro
class Person(name):
def __init__(self,name):
self.name= name
self.lastName = name.split(β β)[-1]
self.birthday = None
def __It__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName #Return True if the lastname is smaller
def setBirthday(self, month, day. year):
self.birthday = date tame.date(year,month,day)
def getAge(self):
return (date time.date.today() - self.birthday).days
class MITPerson(Person):
nextIdNum = 0 # Attribute of the Class
def __init__(self, name):
Person.__init__(self,name)
self.idNum = MITPerson.nextIdNum β> Accedemos al atributo de la clase
MITPerson.nextIdNum += 1 #Attribute of the class +1
def __it__(self, other):
return self.idNum < other.idNum
map, zip, filter, lambda, sorted e one-liners
Map Γ¨ come: [f(x) for x in iterable] β> map(tutple,[a,b]) = [(1,2,3),(4,5)]
m = map(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) β> [False, False, True, False, False, True, False, False, True]
zip si ferma quando il piΓΉ corto tra foo o bar si ferma:
for f, b in zip(foo, bar):
print(f, b)
Lambda viene utilizzato per definire una funzione
(lambda x,y: x+y)(5,3) = 8 β> Usa lambda come semplice funzione
sorted(range(-5,6), key=lambda x: x** 2) = [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5] β> Usa lambda per ordinare una lista
m = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) = [3, 6, 9] β> Usa lambda per filtrare
reduce (lambda x,y: x*y, [1,2,3,4]) = 24
def make_adder(n):
return lambda x: x+n
plus3 = make_adder(3)
plus3(4) = 7 # 3 + 4 = 7
class Car:
crash = lambda self: print('Boom!')
my_car = Car(); my_car.crash() = 'Boom!'
mult1 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x%3 == 0 ]
Eccezioni
def divide(x,y):
try:
result = x/y
except ZeroDivisionError, e:
print βdivision by zero!β + str(e)
except TypeError:
divide(int(x),int(y))
else:
print βresult iβ, result
finally
print βexecuting finally clause in any caseβ
Assert()
Se la condizione Γ¨ falsa, la stringa verrΓ stampata sullo schermo.
def avg(grades, weights):
assert not len(grades) == 0, 'no grades data'
assert len(grades) == 'wrong number grades'
Generatori, yield
Un generatore, invece di restituire qualcosa, βproduceβ qualcosa. Quando lo accedi, βrestituirΓ β il primo valore generato, poi, puoi accedervi di nuovo e restituirΓ il prossimo valore generato. Quindi, tutti i valori non vengono generati contemporaneamente e molta memoria potrebbe essere risparmiata utilizzando questo invece di una lista con tutti i valori.
def myGen(n):
yield n
yield n + 1
g = myGen(6) β> 6
next(g) β> 7
next(g) β> Errore
Espressioni Regolari
import re
re.search(β\wβ,βholaβ).group() = βhβ
re.findall(β\wβ,βholaβ) = [βhβ, βoβ, βlβ, βaβ]
re.findall(β\w+(la)β,βhola caracolaβ) = [βlaβ, βlaβ]
Significati speciali:
. β> Tutto
\w β> [a-zA-Z0-9_]
\d β> Numero
\s β> Carattere di spazi bianchi[ \n\r\t\f]
\S β> Carattere non bianco
^ β> Inizia con
$ β> Finisce con
+ β> Uno o piΓΉ
* β> 0 o piΓΉ
? β> 0 o 1 occorrenze
Opzioni:
re.search(pat,str,re.IGNORECASE)
IGNORECASE
DOTALL β> Consente al punto di corrispondere a una nuova riga
MULTILINE β> Consente a ^ e $ di corrispondere in righe diverse
re.findall(β<.*>β, β<b>foo</b>and<i>so on</i>β) = [β<b>foo</b>and<i>so on</i>β]
re.findall(β<.*?>β, β<b>foo</b>and<i>so on</i>β) = [β<b>β, β</b>β, β<i>β, β</i>β]
IterTools
product
from itertools import product β> Genera combinazioni tra 1 o piΓΉ liste, forse ripetendo valori, prodotto cartesiano (proprietΓ distributiva)
print list(product([1,2,3],[3,4])) = [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
print list(product([1,2,3],repeat = 2)) = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
permutations
from itertools import permutations β> Genera combinazioni di tutti i caratteri in ogni posizione
print list(permutations([β1β,β2β,β3β])) = [(β1β, β2β, β3β), (β1β, β3β, β2β), (β2β, β1β, β3β),β¦ Ogni possibile combinazione
print(list(permutations(β123β,2))) = [(β1β, β2β), (β1β, β3β), (β2β, β1β), (β2β, β3β), (β3β, β1β), (β3β, β2β)] Ogni possibile combinazione di lunghezza 2
combinations
from itertools import combinations β> Genera tutte le possibili combinazioni senza ripetere caratteri (se βabβ esiste, non genera βbaβ)
print(list(combinations(β123β,2))) β> [(β1β, β2β), (β1β, β3β), (β2β, β3β)]
combinations_with_replacement
from itertools import combinations_with_replacement β> Genera tutte le possibili combinazioni a partire dal carattere (ad esempio, il 3Β° Γ¨ mescolato a partire dal 3Β° ma non con il 2Β° o il 1Β°)
print(list(combinations_with_replacement(β1133β,2))) = [(β1β, β1β), (β1β, β1β), (β1β, β3β), (β1β, β3β), (β1β, β1β), (β1β, β3β), (β1β, β3β), (β3β, β3β), (β3β, β3β), (β3β, β3β)]
Decoratori
Decoratore che misura il tempo necessario per eseguire una funzione (da qui):
from functools import wraps
import time
def timeme(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Let's call our decorated function")
start = time.time()
result = func(*args, **kwargs)
print('Execution time: {} seconds'.format(time.time() - start))
return result
return wrapper
@timeme
def decorated_func():
print("Decorated func!")
Se lo esegui, vedrai qualcosa di simile al seguente:
Let's call our decorated function
Decorated func!
Execution time: 4.792213439941406e-05 seconds
Tip
Impara e pratica il hacking AWS:
HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP:HackTricks Training GCP Red Team Expert (GRTE)
Impara e pratica il hacking Azure:
HackTricks Training Azure Red Team Expert (AzRTE)
Supporta HackTricks
- Controlla i piani di abbonamento!
- Unisciti al π¬ gruppo Discord o al gruppo telegram o seguici su Twitter π¦ @hacktricks_live.
- Condividi trucchi di hacking inviando PR ai HackTricks e HackTricks Cloud repos github.
HackTricks

