經過Python中的requests模塊也能夠來發送HTTP請求,接收HTTP響應,從而實現一些更加靈活的操做。
requests是第三方庫,不過在Kali中已經自帶了該模塊。Python3和Python2的用法稍微有些差異,這裏先以Python2爲例。
root@kali:~# pythonhtml
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模塊的用法。python
1.Get請求
利用requests模塊中的get方法,向目標url發送Get請求,將結果賦值給變量r1,直接查看r1的值,將顯示狀態碼。查看text屬性能夠得到HTTP響應正文。經過print()函數輸出,能夠解析其中的換行符。linux
>>> 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請求,參數要以字典的形式表示:nginx
>>> 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中:ide
>>> 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屬性能夠得到響應頭,能夠看到響應頭中的信息是以字典的形式存放:post
>>> 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循環對字典中的鍵進行遍歷:url
>>> for key in r1.headers: ... print(key) ... Server Date Content-Type Transfer-Encoding Connection Keep-Alive Content-Encoding
遍歷鍵和值:code
>>> 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')
查看指定的鍵值:orm
>>> r1.headers['Server'] 'nginx'
查看request.headers屬性能夠得到請求頭:
>>> r1.request.headers {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.18.4'}