目录
一、发送的思路
利用import hashlib,import time,import requests这三个模块
根据时间是戳是唯一的做md5的加密,
获取当前时间,当前时间和字符串拼接
import requests
import hashlib
import time
#获取当前时间
#当前时间和字符串拼接
current_time = time.time()
app_id = "299095cc-1330-11e5-b06a-a45e60bec08b"
v = "%s|%s"%(app_id,current_time)
对拼接的字符串加密
m = hashlib.md5()
m.update(bytes(v,encoding="utf-8"))
authkey = m.hexdigest()
把当前时间和加密好的字符串进行拼接
authkey_time = "%s|%s"%(authkey,current_time)
通过requests发送
host_data = {
'status':True,
'data':{
'hostname':'c1.com',
'disk':{'status':True,'data':'xxxxx'},
'men':{'status':True,'data':'xxxxx'},
'nic':{'status':True,'data':'xxxxx'},
}
}
#通过请求头返回给后台
response = requests.post(
url='http://127.0.0.1:8000/api/asset/',
json=host_data,
headers = {'authkey':authkey_time}
)
print(response.text)
二、接受的思路
post的请求通过request.body来获取,header通过request.META获取
def asset(request):
if request.method == "POST":
auth_list = []
# 获取post请求过来的参数
host_info = json.loads(str(request.body, encoding="utf-8"))
#获取header发送过来的加密字符串
auth_key_time = request.META['HTTP_AUTHKEY']
#通过分割,分别获取md5的加密和脚本的时间
auth_key, client_ctime = auth_key_time.split("|")
server_time =time.time()
第一层判断,判断服务器时间和脚本时间的时间差
第二层判断,判断同样的时间戳确保只能访问一次
服务器端的ck+脚本时间戳md5的加密但等同于脚本的md5
把用过的时间戳假如,超过十秒的排除
if server_time-10>float(client_ctime):
return HttpResponse('访问失败')
elif auth_key_time in auth_list:
return HttpResponse('访问失败')
v = "%s|%s" % (ck, client_ctime)
m = hashlib.md5()
m.update(bytes(v, encoding="utf-8"))
server_key = m.hexdigest()
if server_key !=host_info:
return HttpResponse('无权限')
auth_list.append(client_ctime)
for i in auth_list:
if server_time-10>float(client_ctime):
auth_list.pop(i)
三、代码
脚本
import requests
import hashlib
import time
#获取当前时间
#当前时间和字符串拼接
current_time = time.time()
app_id = "299095cc-1330-11e5-b06a-a45e60bec08b"
v = "%s|%s"%(app_id,current_time)
#对拼接的字符串加密
m = hashlib.md5()
m.update(bytes(v,encoding="utf-8"))
authkey = m.hexdigest()
#把当前时间和加密好的字符串进行拼接
authkey_time = "%s|%s"%(authkey,current_time)
host_data = {
'status':True,
'data':{
'hostname':'c1.com',
'disk':{'status':True,'data':'xxxxx'},
'men':{'status':True,'data':'xxxxx'},
'nic':{'status':True,'data':'xxxxx'},
}
}
#通过请求头返回给后台
response = requests.post(
url='http://127.0.0.1:8000/api/asset/',
json=host_data,
headers = {'authkey':authkey_time}
)
print(response.text)
服务器端
def asset(request):
if request.method == "POST":
auth_list = []
host_info = json.loads(str(request.body, encoding="utf-8"))
auth_key_time = request.META['HTTP_AUTHKEY']
auth_key, client_ctime = auth_key_time.split("|")
server_time =time.time()
if server_time-10>float(client_ctime):
return HttpResponse('访问失败')
elif auth_key_time in auth_list:
return HttpResponse('访问失败')
v = "%s|%s" % (ck, client_ctime)
m = hashlib.md5()
m.update(bytes(v, encoding="utf-8"))
server_key = m.hexdigest()
if server_key !=host_info:
return HttpResponse('无权限')
auth_list.append(client_ctime)
for i in auth_list:
if server_time-10>float(client_ctime):
auth_list.pop(i)
return HttpResponse('.....')