f10@t's blog

CTF中的python脚本题小结(一)

字数统计: 1.9k阅读时长: 10 min
2018/10/30

每次遇到有关于写脚本的题都不能很好的做出来。。。这里总结一下

最基本的requests库

首先我们需要一点网络编程的基础。这是requests库的所有模块和函数:

1
['ConnectTimeout', 'ConnectionError', 'DependencyWarning', 'FileModeWarning', 'HTTPError', 'NullHandler', 'PreparedRequest', 'ReadTimeout', 'Request', 'RequestException', 'RequestsDependencyWarning', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__author_email__', '__build__', '__builtins__', '__cached__', '__cake__', '__copyright__', '__description__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__title__', '__url__', '__version__', '_check_cryptography', '_internal_utils', 'adapters', 'api', 'auth', 'certs', 'chardet', 'check_compatibility', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'urllib3', 'utils', 'warnings']
requests库使用来干什么的呢?
1
2
3
4
5
6
7
8
9
10
Help on package requests:

NAME
requests

DESCRIPTION
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~

Requests is an HTTP library, written in Python, for human beings.
简单明了。下面我们从基本请求,响应,一些常用功能如从响应中获取cookies,响应头信息等,以及如文件上传等操作。  ### 请求 #### GET请求   1. 基本写法:
1
2
3
4
5
6
import requests

url = "http://httpbin.org/get"
response = requests.get(url)
print (response.stauts_code)
print (response.text)
  结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
200

{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.19.1"
},
"origin": "xxxx",
"url": "https://httpbin.org/get"
}
  2. 带有参数的GET请求。写法一:
1
2
3
4
5
6
7
import requests

# 直接将参数写入
url = "http://httpbin.org/get?word=xixixixi"

response = requests.get(url)
print (requests.text)
结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"args": {
"word": "xixixixi"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.19.1"
},
"origin": "xxxx",
"url": "http://httpbin.org/get?word=xixixixi"
}
写法二:
1
2
3
4
5
6
7
8
9
10
11
import requests

# 将参数依次以下面的格式写入
param = {
'word1':'xixixixixi',
'word2':'hahahahaha'
}

url = "http://httpbin.org/get"
response = requests.get(url,params=param)
print (requests.text)
结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"args": {
"word1": "xixixixixi",
"word2": "hahahahaha"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.19.1"
},
"origin": "xxxx",
"url": "http://httpbin.org/get?word1=xixixixixi&word2=hahahahaha"
}

POST请求

写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests

# 写入post表单信息
data = {
'word1':'hahaha',
'word2':'xixixi'
}
# 设置请求头信息
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
}
url = "http://httpbin.org/post"
response = requests.post(url,data=data,headers=headers)

print(response.text)
结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"args": {},
"data": "",
"files": {},
"form": {
"word1": "hahaha",
"word2": "xixixi"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "25",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"
},
"json": null,
"origin": "xxxx",
"url": "http://httpbin.org/post"
}

其他功能

解析json
1
2
3
4
5
6
7
8
9
10
11
import requests

response = requests.get('http://httpbin.org/get')
# 获取响应内容
print(type(response.text))

# 如果响应内容是json,就将其转为json
print(response.json())

# 输出的是字典类型
print(type(response.json()))
获取二进制数据
1
2
3
4
5
6
7
8
9
10
11
import requests
response = requests.get('http://github.com/favicon.ico')
# str,bytes
print(type(response.text),type(response.content))
print(response.text)
# 二进制内容
print(response.content)
# 下载二进制数据到本地
with open('favicon.ico','wb') as f:
f.write(response.content)
f.close()

响应

response属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import requests
response = requests.get('http://www.baidu.com/')
# 获取响应状态码
print(type(response.status_code),response.status_code)

<class 'int'> 200


# 获取响应头信息
print(type(response.headers),response.headers)

<class 'requests.structures.CaseInsensitiveDict'>

{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Tue, 30 Oct 2018 11:24:10 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:36 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

# 获取响应头中的cookies
print(type(response.cookies),response.cookies)

<class 'requests.cookies.RequestsCookieJar'>

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>

# 获取访问的url
print(type(response.url),response.url)

<class 'str'>

http://www.baidu.com/

# 获取访问的历史记录
print(type(response.history),response.history)

<class 'list'>

[]

  下面是requests内置的所有状态字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),

# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0

# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),

# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication')

高级操作

文件上传

1
2
3
4
5
6
7
8
import requests

files = {
'file':open('1.txt','rb')
}
url = "http://httpbin.org/get"
response = requests.get(url,files=files)
print(response.text)

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "500",
"Content-Type": "multipart/form-data; boundary=592e015eed01c47f9d7c40b7eb8f9019",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.19.1"
},
"origin": "xxxx",
"url": "http://httpbin.org/get"
}
#### 会话维持
1
2
3
4
5
6
7
8
9
10
11

import requests

session = requests.session()

# Sends a GET request. Returns :class:`Response` object.
session.get('http://httpbin.org/cookies/set/number/12456')
# <Response [200]>

response = session.get('http://httpbin.org/cookies')
print(response.text)
结果:
1
2
3
4
5
{
"cookies": {
"number": "12456"
}
}
关于session():
1
2
3
4
5
6
7
Help on Session in module requests.sessions object:

class Session(SessionRedirectMixin)

A Requests session.

Provides cookie persistence, connection-pooling, and configuration.

CATALOG
  1. 1. 最基本的requests库
    1. 1.0.1. POST请求
    2. 1.0.2. 其他功能
      1. 1.0.2.1. 解析json
      2. 1.0.2.2. 获取二进制数据
  2. 1.1. 响应
    1. 1.1.1. response属性:
  3. 1.2. 高级操作
    1. 1.2.1. 文件上传