security
CHAPTER 62 / 84
읽기 약 2분
FUNCTION
Requests 라이브러리 완전 정복
핵심 개념
Python으로 HTTP 요청을 보내고 응답을 분석하는 핵심 도구를 마스터한다.
본문
requests 기본 패턴
# ⚠️ 이 코드는 허가된 환경에서만 사용하세요.
import requests
# GET — 쿼리 파라미터 자동 인코딩
r = requests.get(
'https://httpbin.org/get',
params={'q': 'security', 'page': 1},
headers={'User-Agent': 'WhiteHat/1.0'},
timeout=5,
)
print(r.url) # https://httpbin.org/get?q=security&page=1
print(r.status_code) # 200
print(r.json()) # 자동 JSON 파싱
# POST — 폼 데이터
r = requests.post(
'https://httpbin.org/post',
data={'username': 'test', 'password': 'p@ssw0rd'},
)
# POST — JSON 본문
r = requests.post(
'https://httpbin.org/post',
json={'username': 'test', 'role': 'user'},
)헤더 커스텀과 SSL 검증
# 보안 점검에서 자주 쓰는 헤더 변조
HEADERS = {
'User-Agent': 'Mozilla/5.0',
'X-Forwarded-For': '127.0.0.1', # WAF 우회 시도 — 허가 환경에서만
'Referer': 'https://internal.example.com',
}
# SSL 검증 — 운영에서는 절대 verify=False 금지
r = requests.get('https://expired.badssl.com', verify=True, timeout=5)
# 인증서 직접 지정 (사내 CA)
r = requests.get('https://internal.com', verify='/path/to/internal-ca.pem')타임아웃의 종류
# (connect_timeout, read_timeout)
r = requests.get(url, timeout=(3, 10))
# 단일 timeout=5는 연결+읽기 모두에 5초프록시 설정 — Burp Suite 연동
# 보안 분석 도구 Burp Suite를 통해 트래픽 캡처
proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'http://127.0.0.1:8080',
}
r = requests.get(
'https://example.com',
proxies=proxies,
verify=False, # Burp의 자체 서명 인증서 → 학습용만
timeout=5,
)보안 헤더 자동 점검
def check_security_headers(url: str) -> dict:
"""웹사이트의 보안 헤더 5대장 점검."""
expected = {
'Content-Security-Policy': 'CSP',
'Strict-Transport-Security': 'HSTS',
'X-Frame-Options': 'Clickjacking',
'X-Content-Type-Options': 'MIME-Sniff',
'Referrer-Policy': 'Referer',
}
try:
r = requests.get(url, timeout=5, allow_redirects=True)
except requests.exceptions.RequestException as e:
return {'error': str(e)}
result = {'url': r.url, 'status': r.status_code, 'headers': {}}
for hdr, label in expected.items():
present = hdr in r.headers
result['headers'][label] = {
'present': present,
'value': r.headers.get(hdr) if present else None,
}
score = sum(1 for h in result['headers'].values() if h['present'])
result['score'] = f'{score}/{len(expected)}'
return result
# 실행
import json
report = check_security_headers('https://github.com')
print(json.dumps(report, indent=2, ensure_ascii=False))Response 객체 활용
r = requests.get('https://api.github.com/users/octocat')
# 기본 속성
r.status_code # 200
r.headers # CaseInsensitiveDict
r.cookies # RequestsCookieJar
r.url # 최종 URL (리다이렉트 후)
r.elapsed # timedelta — 응답 시간
r.history # 리다이렉트 체인
# 본문 접근 (3가지)
r.text # 문자열
r.content # bytes
r.json() # dict (실패 시 ValueError)
# 안전한 JSON 파싱
try:
data = r.json()
except ValueError:
data = None
log.warning('JSON 파싱 실패')AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내가 작성한 보안 헤더 점검 스크립트를 분석해서 누락된 케이스(리다이렉트/타임아웃/SSL)를 프로덕션 수준으로 개선해줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
requests 라이브러리로 보안 점검 시 자주 쓰는 패턴 10개 (쿠키 추적/프록시/헤더 변조/SSL 우회 등)를 복사 가능한 코드로 정리해줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 모든 도메인 자산에 대해 보안 헤더 점검을 일괄 실행하고 경영진 보고용 종합 리포트(점수+개선 우선순위)를 만들어줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 웹 자동화에서 requests vs httpx vs aiohttp 실무 채택률과 성능 차이를 솔직히 알려줘.
⭐ 이것만 기억하세요
Requests 라이브러리 완전 정복은 이 3가지만 확실히 잡으세요
1.requests로 GET/POST/헤더/쿠키/프록시를 자유롭게 다루면 모든 웹 보안 점검의 80%가 가능해진다
2.보안 헤더 자동 점검 함수만으로도 실용 가치 있는 미니 도구를 만들 수 있다
3.다음 챕터에서 세션과 쿠키를 깊이 분석해 인증 우회 공격의 원리를 이해한다
공유하기
진행도 62 / 84