AWSElastic'GET'API请求使用URL--Python3.8||AuthAWSSignature改为中文
创始人
2024-09-25 07:02:12
0

以下是使用Python 3.8和AWS签名身份验证对AWS Elastic的GET API请求进行URL编码的示例代码:

import requests
import datetime
import hashlib
import hmac
import urllib.parse

# AWS Key
ACCESS_KEY = 'YOUR_ACCESS_KEY'
SECRET_KEY = 'YOUR_SECRET_KEY'

# Parameter values for the request
method = 'GET'
service = 'ec2'
host = 'ec2.amazonaws.com'
region = 'us-east-1'
endpoint = 'https://ec2.amazonaws.com'

# Define the request parameters
params = {'Action': 'DescribeRegions',
          'Version': '2013-10-15'}

# Define the date and time variable
t = datetime.datetime.utcnow()
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')

# Create the canonical query string
canonical_querystring = ''
for param in sorted(params.items()):
    canonical_querystring += urllib.parse.quote(param[0], safe='') + '=' + urllib.parse.quote(param[1], safe='') + '&'

# Create the canonical headers and signed headers
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

# Create the canonical request and hash it
canonical_request = method + '\n' + '/' + '\n' + canonical_querystring[:-1] + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
hashed_canonical_request = hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

# Create the string to sign
string_to_sign = 'AWS4-HMAC-SHA256' + '\n' + amz_date + '\n' + datestamp + '/' + region + '/' + service + '/' + 'aws4_request' + '\n' + hashed_canonical_request

# Create the signing key with the crucial date
kDate = hmac.new(('AWS4' + SECRET_KEY).encode('utf-8'), datestamp.encode('utf-8'), hashlib.sha256).digest()
kRegion = hmac.new(kDate, region.encode('utf-8'), hashlib.sha256).digest()
kService = hmac.new(kRegion, service.encode('utf-8'), hashlib.sha256).digest()
kSigning = hmac.new(kService, b'aws4_request', hashlib.sha256).digest()

# Create the signature
signature = hmac.new(kSigning, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()

# Create the authorization header
authorization_header = '

相关内容

热门资讯

iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
iphone系统与安卓系统更新... 最近是不是你也遇到了这样的烦恼?手机更新系统总是失败,急得你团团转。别急,今天就来给你揭秘为什么iP...
oppo手机安卓系统换成苹果系... OPPO手机安卓系统换成苹果系统:现实吗?如何操作?随着智能手机市场的不断发展,用户对于手机系统的需...
安卓平板改windows 系统... 你有没有想过,你的安卓平板电脑是不是也能变身成Windows系统的超级英雄呢?想象在同一个设备上,你...
安卓系统上滑按键,便捷生活与高... 你有没有发现,现在手机屏幕越来越大,操作起来却越来越方便了呢?这都得归功于安卓系统上的那些神奇的上滑...
安卓系统连接耳机模式,蓝牙、有... 亲爱的手机控们,你们有没有遇到过这种情况:手机突然变成了“耳机模式”,明明耳机没插,声音却只从耳机孔...
安卓换鸿蒙系统会卡吗,体验流畅... 最近手机圈可是热闹非凡呢!不少安卓用户都在议论纷纷,说鸿蒙系统要来啦!那么,安卓手机换上鸿蒙系统后,...
希沃系统怎么装安卓系统,解锁更... 亲爱的读者们,你是否也像我一样,对希沃一体机上的安卓系统充满了好奇呢?想象在教室里,你的希沃一体机不...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...