1. 程式人生 > >HTTP協議(9)Python requests模組的使用

HTTP協議(9)Python requests模組的使用

通過Python中的requests模組也可以來發送HTTP請求,接收HTTP響應,從而實現一些更加靈活的操作。
requests是第三方庫,不過在Kali中已經自帶了該模組。Python3和Python2的用法稍微有些差別,這裡先以Python2為例。
[email protected]:~# python

Python 2.7.15 (default, Jul 28 2018, 11:29:29) 
[GCC 8.1.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import requests

下面以之前做過的Bugku中的Get和Post方法兩道題目為例,來介紹requests模組的用法。

1.Get請求
利用requests模組中的get方法,向目標url傳送Get請求,將結果賦值給變數r1,直接檢視r1的值,將顯示狀態碼。檢視text屬性可以獲得HTTP響應正文。通過print()函式輸出,可以解析其中的換行符。

>>> r1=requests.get(url='http://123.206.87.240:8002/get/')
>>> r1
<Response [200]>
>>> r1.text
u"$what=$_GET['what'];<br>\r\necho $what;<br>\r\nif($what=='flag')<br>\r\necho 'flag{****}';<br>\r\n\r\n\r\n"
>>> print(r1.text)
$what=$_GET['what'];<br>
echo $what;<br>
if($what=='flag')<br>
echo 'flag{****}';<br>

下面傳送帶引數的Get請求,引數要以字典的形式表示:

>>> r1=requests.get(url='http://123.206.87.240:8002/get/',params={'what':'flag'})
>>> print(r1.text)
$what=$_GET['what'];<br>
echo $what;<br>
if($what=='flag')<br>
echo 'flag{****}';<br>

flagflag{bugku_get_su8kej2en}

2.Post請求
仍是向目標url傳送Post請求,並將結果儲存在變數r2中:

>>> r2=requests.post(url='http://123.206.87.240:8002/post/')
>>> print(r2.text)
$what=$_POST['what'];<br>
echo $what;<br>
if($what=='flag')<br>
echo 'flag{****}';<br>

傳送帶引數的Post請求:

>>> r2=requests.post(url='http://123.206.87.240:8002/post/',data={'what':'flag'})
>>> print(r2.text)
$what=$_POST['what'];<br>
echo $what;<br>
if($what=='flag')<br>
echo 'flag{****}';<br>

flagflag{bugku_get_ssseint67se}

3.檢視報文頭
檢視headers屬性可以獲得響應頭,可以看到響應頭中的資訊是以字典的形式存放:

>>> r1.headers
{'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Keep-Alive': 'timeout=60', 'Server': 'nginx', 'Connection': 'keep-alive', 'Date': 'Tue, 04 Dec 2018 23:12:33 GMT', 'Content-Type': 'text/html'}

通過for迴圈對字典中的鍵進行遍歷:

>>> for key in r1.headers:
...     print(key)
... 
Server
Date
Content-Type
Transfer-Encoding
Connection
Keep-Alive
Content-Encoding

遍歷鍵和值:

>>> for key in r1.headers:
...     print(key,r1.headers[key])
... 
('Server', 'nginx')
('Date', 'Tue, 04 Dec 2018 23:12:33 GMT')
('Content-Type', 'text/html')
('Transfer-Encoding', 'chunked')
('Connection', 'keep-alive')
('Keep-Alive', 'timeout=60')
('Content-Encoding', 'gzip')

檢視指定的鍵值:

>>> r1.headers['Server']
'nginx'

檢視request.headers屬性可以獲得請求頭:

>>> r1.request.headers
{'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.18.4'}