在python2中创建AWS SES SMTP凭证



我正在从我的iam accesskey和secretkey创建SES SMTP凭据。我参考了这个文档来创建SES SMTP凭据

但是代码为python2和python3生成不同的SES SMTP凭据,但python3密钥是有效的。在使用python2执行脚本时,我如何获得相同的键下面是我的脚本,它返回accesskey和SES SMTP信用。我从秘密管理器

获得Iam访问密钥和秘密密钥
#!/usr/bin/env python3
import hmac
import hashlib
import base64
import argparse
import boto3
import json
from botocore.exceptions import ClientError
def get_secretmanager():
secret_name = "test"
region_name = "us-west-2"
session = boto3.session.Session()
client = session.client(
service_name='secretsmanager',
region_name=region_name
)
try:
get_secret_value_response = client.get_secret_value(
SecretId=secret_name
)
except ClientError as e:
raise e
# Decrypts secret using the associated KMS key.
secret = get_secret_value_response['SecretString']
response = json.loads(secret)
return str(response['Access Key Id']), str(response['Secret Access Key'])
SMTP_REGIONS = [
'us-east-2',       # US East (Ohio)
'us-east-1',       # US East (N. Virginia)
'us-west-2',       # US West (Oregon)
'ap-south-1',      # Asia Pacific (Mumbai)
'ap-northeast-2',  # Asia Pacific (Seoul)
'ap-southeast-1',  # Asia Pacific (Singapore)
'ap-southeast-2',  # Asia Pacific (Sydney)
'ap-northeast-1',  # Asia Pacific (Tokyo)
'ca-central-1',    # Canada (Central)
'eu-central-1',    # Europe (Frankfurt)
'eu-west-1',       # Europe (Ireland)
'eu-west-2',       # Europe (London)
'sa-east-1',       # South America (Sao Paulo)
'us-gov-west-1',   # AWS GovCloud (US)
]
# These values are required to calculate the signature. Do not change them.
DATE = "11111111"
SERVICE = "ses"
MESSAGE = "SendRawEmail"
TERMINAL = "aws4_request"
VERSION = 0x04
def sign(key, msg):
return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
def calculate_key(secret_access_key, region):
if region not in SMTP_REGIONS:
raise ValueError("The " + region+ " Region doesn't have an SMTP endpoint.")
signature = sign(("AWS4" + secret_access_key).encode('utf-8'), DATE)
signature = sign(signature, region)
signature = sign(signature, SERVICE)
signature = sign(signature, TERMINAL)
signature = sign(signature, MESSAGE)
signature_and_version = bytes([VERSION]) + signature
smtp_password = base64.b64encode(signature_and_version)
print(smtp_password)
return smtp_password.decode('utf-8')
def get_keys():
accesskey, secretkey = get_secretmanager() 
mailsecret = calculate_key(secretkey, "us-west-2")
return accesskey, mailsecret
print(get_keys())

任何帮助都是非常感激的,谢谢你

经过大量的调试,我发现bytes([VERSION])在python3和python2中都不工作,这就是为什么它为2和3返回2个不同的值我的简单修复是将十六进制0x04的字节值硬编码为b'x04'

signature_and_version = b'x04' + signature

确保以字符串return accesskey, str(mailsecret)返回值,因为在python2中它以unicode返回。

最新更新