Basic Python

Tip

AWS ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°:HackTricks Training AWS Red Team Expert (ARTE)
GCP ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°: HackTricks Training GCP Red Team Expert (GRTE) Azure ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks μ§€μ›ν•˜κΈ°

Python Basics

μœ μš©ν•œ 정보

list(xrange()) == range() –> Python3μ—μ„œ rangeλŠ” Python2의 xrangeμž…λ‹ˆλ‹€ (λ¦¬μŠ€νŠΈκ°€ μ•„λ‹ˆλΌ μ œλ„ˆλ ˆμ΄ν„°μž…λ‹ˆλ‹€)
νŠœν”Œκ³Ό 리슀트의 μ°¨μ΄λŠ” νŠœν”Œμ—μ„œ κ°’μ˜ μœ„μΉ˜κ°€ 의미λ₯Ό λΆ€μ—¬ν•˜μ§€λ§Œ λ¦¬μŠ€νŠΈλŠ” λ‹¨μˆœνžˆ μ •λ ¬λœ κ°’μ΄λΌλŠ” κ²ƒμž…λ‹ˆλ‹€. νŠœν”Œμ€ ꡬ쑰λ₯Ό κ°€μ§€μ§€λ§Œ λ¦¬μŠ€νŠΈλŠ” μˆœμ„œλ₯Ό κ°€μ§‘λ‹ˆλ‹€.

μ£Όμš” μ—°μ‚°

숫자λ₯Ό μ œκ³±ν•˜λ €λ©΄: 3**2λ₯Ό μ‚¬μš©ν•©λ‹ˆλ‹€ (3^2이 μ•„λ‹˜)
2/3을 ν•˜λ©΄ 1이 λ°˜ν™˜λ©λ‹ˆλ‹€. μ™œλƒν•˜λ©΄ 두 개의 μ •μˆ˜(int)λ₯Ό λ‚˜λˆ„κ³  있기 λ•Œλ¬Έμž…λ‹ˆλ‹€. μ†Œμˆ˜μ μ΄ ν•„μš”ν•˜λ©΄ 뢀동 μ†Œμˆ˜μ (float)을 λ‚˜λˆ„μ–΄μ•Ό ν•©λ‹ˆλ‹€ (2.0/3.0).
i >= j
i <= j
i == j
i != j
a and b
a or b
not 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) = μ‚¬μš© κ°€λŠ₯ν•œ λͺ¨λ“  λ©”μ†Œλ“œμ˜ λͺ©λ‘
help(str) = str 클래슀의 μ •μ˜
β€œa”.upper() = β€œA”
β€œA”.lower() = β€œa”
β€œabc”.capitalize() = β€œAbc”
sum([1,2,3]) = 6
sorted([1,43,5,3,21,4])

문자 κ²°ν•©
3 * ’a’ = β€˜aaa’
β€˜a’ + β€˜b’ = β€˜ab’
β€˜a’ + str(3) = β€˜a3’
[1,2,3]+[4,5]=[1,2,3,4,5]

리슀트의 λΆ€λΆ„
β€˜abc’[0] = β€˜a’
’abc’[-1] = β€˜c’
’abc’[1:3] = β€˜bc’ (인덱슀 [1]λΆ€ν„° [2]κΉŒμ§€)
β€œqwertyuiop”[:-1] = β€˜qwertyuio’

주석
# ν•œ 쀄 주석
β€œβ€β€œ
μ—¬λŸ¬ 쀄 주석
또 λ‹€λ₯Έ 주석
β€œβ€β€œ

루프

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"

νŠœν”Œ

t1 = (1,’2,β€˜three’)
t2 = (5,6)
t3 = t1 + t2 = (1, β€˜2’, β€˜three’, 5, 6)
(4,) = 싱글톀
d = () 빈 νŠœν”Œ
d += (4,) –> νŠœν”Œμ— μΆ”κ°€
CANT! –> t1[1] == β€˜New value’
list(t2) = [5,6] –> νŠœν”Œμ—μ„œ 리슀트둜

리슀트 (λ°°μ—΄)

d = [] 빈
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) –> λ¦¬μŠ€νŠΈμ—μ„œ νŠœν”Œλ‘œ

λ”•μ…”λ„ˆλ¦¬

d = {} 빈
monthNumbers={1:’Jan’, 2: β€˜feb’,’feb’:2}β€”> monthNumbers ->{1:’Jan’, 2: β€˜feb’,’feb’:2}
monthNumbers[1] = β€˜Jan’
monthNumbers[β€˜feb’] = 2
list(monthNumbers) = [1,2,’feb’]
monthNumbers.values() = [β€˜Jan’,’feb’,2]
keys = [k for k in monthNumbers]
a={β€˜9’:9}
monthNumbers.update(a) = {β€˜9’:9, 1:’Jan’, 2: β€˜feb’,’feb’:2}
mN = monthNumbers.copy() #독립 볡사
monthNumbers.get(β€˜key’,0) #ν‚€ 쑴재 μ—¬λΆ€ 확인, monthNumbers[β€œkey”]의 κ°’ λ°˜ν™˜ λ˜λŠ” μ‘΄μž¬ν•˜μ§€ μ•ŠμœΌλ©΄ 0 λ°˜ν™˜

μ§‘ν•©

μ§‘ν•©μ—λŠ” 쀑볡이 μ—†μŒ
myset = set([β€˜a’, β€˜b’]) = {β€˜a’, β€˜b’}
myset.add(β€˜c’) = {β€˜a’, β€˜b’, β€˜c’}
myset.add(β€˜a’) = {β€˜a’, β€˜b’, β€˜c’} #쀑볡 μ—†μŒ
myset.update([1,2,3]) = set([β€˜a’, 1, 2, β€˜b’, β€˜c’, 3])
myset.discard(10) #μ‘΄μž¬ν•˜λ©΄ 제거, μ—†μœΌλ©΄ 아무것도 ν•˜μ§€ μ•ŠμŒ
myset.remove(10) #μ‘΄μž¬ν•˜λ©΄ 제거, μ—†μœΌλ©΄ μ˜ˆμ™Έ λ°œμƒ
myset2 = set([1, 2, 3, 4])
myset.union(myset2) #myset λ˜λŠ” myset2의 κ°’
myset.intersection(myset2) #myset 및 myset2의 κ°’
myset.difference(myset2) #myset의 κ°’μ΄μ§€λ§Œ myset2μ—λŠ” μ—†μŒ
myset.symmetric_difference(myset2) #myset 및 myset2에 μ—†λŠ” κ°’ (λ‘˜ λ‹€ μ•„λ‹˜)
myset.pop() #μ§‘ν•©μ˜ 첫 번째 μš”μ†Œλ₯Ό κ°€μ Έμ™€μ„œ 제거
myset.intersection_update(myset2) #myset = mysetκ³Ό myset2 λͺ¨λ‘μ— μžˆλŠ” μš”μ†Œ
myset.difference_update(myset2) #myset = myset의 μš”μ†Œμ§€λ§Œ myset2μ—λŠ” μ—†μŒ
myset.symmetric_difference_update(myset2) #myset = λ‘˜ λ‹€ μ•„λ‹Œ μš”μ†Œ

클래슀

__It__의 λ©”μ„œλ“œλŠ” 이 클래슀의 객체가 λ‹€λ₯Έ 객체보닀 큰지 λΉ„κ΅ν•˜λŠ” 데 μ‚¬μš©λ˜λŠ” λ©”μ„œλ“œμž…λ‹ˆλ‹€.

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 and one-liners

MapλŠ” λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€: [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λŠ” foo λ˜λŠ” bar 쀑 짧은 것이 멈좜 λ•Œ 멈μΆ₯λ‹ˆλ‹€:

for f, b in zip(foo, bar):
print(f, b)

LambdaλŠ” ν•¨μˆ˜λ₯Ό μ •μ˜ν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.
(lambda x,y: x+y)(5,3) = 8 –> lambdaλ₯Ό κ°„λ‹¨ν•œ function으둜 μ‚¬μš©
sorted(range(-5,6), key=lambda x: x** 2) = [0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5] –> lambdaλ₯Ό μ‚¬μš©ν•˜μ—¬ 리슀트λ₯Ό μ •λ ¬
m = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9]) = [3, 6, 9] –> lambdaλ₯Ό μ‚¬μš©ν•˜μ—¬ 필터링
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 ]

μ˜ˆμ™Έ

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()

쑰건이 거짓이면 λ¬Έμžμ—΄μ΄ 화면에 좜λ ₯λ©λ‹ˆλ‹€.

def avg(grades, weights):
assert not len(grades) == 0, 'no grades data'
assert len(grades) == 'wrong number grades'

Generators, yield

μ œλ„ˆλ ˆμ΄ν„°λŠ” 무언가λ₯Ό λ°˜ν™˜ν•˜λŠ” λŒ€μ‹  β€œμƒμ„±β€œν•©λ‹ˆλ‹€. μ ‘κ·Όν•  λ•Œ, 첫 번째둜 μƒμ„±λœ 값을 β€œλ°˜ν™˜β€œν•˜κ³ , λ‹€μ‹œ μ ‘κ·Όν•˜λ©΄ λ‹€μŒμœΌλ‘œ μƒμ„±λœ 값을 λ°˜ν™˜ν•©λ‹ˆλ‹€. λ”°λΌμ„œ λͺ¨λ“  값이 λ™μ‹œμ— μƒμ„±λ˜μ§€ μ•ŠμœΌλ©°, λͺ¨λ“  값을 ν¬ν•¨ν•˜λŠ” 리슀트 λŒ€μ‹  이λ₯Ό μ‚¬μš©ν•˜λ©΄ λ§Žμ€ λ©”λͺ¨λ¦¬λ₯Ό μ ˆμ•½ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

def myGen(n):
yield n
yield n + 1

g = myGen(6) –> 6
next(g) –> 7
next(g) –> 였λ₯˜

μ •κ·œ ν‘œν˜„μ‹

import re
re.search(β€œ\w”,β€œhola”).group() = β€œh”
re.findall(β€œ\w”,β€œhola”) = [β€˜h’, β€˜o’, β€˜l’, β€˜a’]
re.findall(β€œ\w+(la)”,β€œhola caracola”) = [β€˜la’, β€˜la’]

νŠΉλ³„ν•œ 의미:
. –> λͺ¨λ“  것
\w –> [a-zA-Z0-9_]
\d –> 숫자
\s –> 곡백 문자[ \n\r\t\f]
\S –> 비곡백 문자
^ –> μ‹œμž‘
$ –> 끝
+ –> ν•˜λ‚˜ 이상
* –> 0개 이상
? –> 0개 λ˜λŠ” 1개 λ°œμƒ

μ˜΅μ…˜:
re.search(pat,str,re.IGNORECASE)
IGNORECASE
DOTALL –> 점이 쀄 λ°”κΏˆκ³Ό μΌμΉ˜ν•˜λ„λ‘ ν—ˆμš©
MULTILINE –> ^와 $κ°€ λ‹€λ₯Έ μ€„μ—μ„œ μΌμΉ˜ν•˜λ„λ‘ ν—ˆμš©

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 –> 1개 μ΄μƒμ˜ 리슀트 κ°„μ˜ 쑰합을 μƒμ„±ν•˜λ©°, 값이 반볡될 수 있고, μΉ΄λ₯΄ν…Œμ‹œμ•ˆ κ³±(λΆ„λ°° 법칙)
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 –> λͺ¨λ“  μœ„μΉ˜μ—μ„œ λͺ¨λ“  문자의 쑰합을 생성
print list(permutations([β€˜1’,β€˜2’,β€˜3’])) = [(β€˜1’, β€˜2’, β€˜3’), (β€˜1’, β€˜3’, β€˜2’), (β€˜2’, β€˜1’, β€˜3’),… λͺ¨λ“  κ°€λŠ₯ν•œ μ‘°ν•©
print(list(permutations(β€˜123’,2))) = [(β€˜1’, β€˜2’), (β€˜1’, β€˜3’), (β€˜2’, β€˜1’), (β€˜2’, β€˜3’), (β€˜3’, β€˜1’), (β€˜3’, β€˜2’)] 길이 2의 λͺ¨λ“  κ°€λŠ₯ν•œ μ‘°ν•©

combinations
from itertools import combinations –> λ¬Έμžκ°€ λ°˜λ³΅λ˜μ§€ μ•ŠλŠ” λͺ¨λ“  κ°€λŠ₯ν•œ 쑰합을 생성(β€œabβ€œκ°€ μ‘΄μž¬ν•˜λ©΄ β€œbaβ€œλŠ” μƒμ„±ν•˜μ§€ μ•ŠμŒ)
print(list(combinations(β€˜123’,2))) –> [(β€˜1’, β€˜2’), (β€˜1’, β€˜3’), (β€˜2’, β€˜3’)]

combinations_with_replacement
from itertools import combinations_with_replacement –> λ¬ΈμžλΆ€ν„° μ‹œμž‘ν•˜μ—¬ λͺ¨λ“  κ°€λŠ₯ν•œ 쑰합을 생성(예: 3λ²ˆμ§ΈλŠ” 3λ²ˆμ§ΈλΆ€ν„° ν˜Όν•©λ˜μ§€λ§Œ 2λ²ˆμ§Έλ‚˜ 첫 λ²ˆμ§Έμ™€λŠ” ν˜Όν•©λ˜μ§€ μ•ŠμŒ)
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’)]

λ°μ½”λ ˆμ΄ν„°

ν•¨μˆ˜κ°€ μ‹€ν–‰λ˜λŠ” 데 ν•„μš”ν•œ μ‹œκ°„μ„ μΈ‘μ •ν•˜λŠ” λ°μ½”λ ˆμ΄ν„° (μ—¬κΈ°μ„œ):

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!")

μ‹€ν–‰ν•˜λ©΄ λ‹€μŒκ³Ό 같은 λ‚΄μš©μ„ λ³Ό 수 μžˆμŠ΅λ‹ˆλ‹€:

Let's call our decorated function
Decorated func!
Execution time: 4.792213439941406e-05 seconds

Tip

AWS ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°:HackTricks Training AWS Red Team Expert (ARTE)
GCP ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°: HackTricks Training GCP Red Team Expert (GRTE) Azure ν•΄ν‚Ή 배우기 및 μ—°μŠ΅ν•˜κΈ°: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks μ§€μ›ν•˜κΈ°