import requests
from requests_aws4auth import AWS4Auth
import base64

# 配置 AWS 认证信息
aws_access_key_id = 'XXX' # AK of IAM user authorized by target elasticsearch for manipulating snapshots
aws_secret_access_key = 'XXX' # SK of IAM user authorized by target elasticsearch for manipulating snapshots
region = 'us-east-1'
service = 'es'  # OpenSearch 的服务标识

# 初始化 AWS4 签名器
awsauth = AWS4Auth(
    aws_access_key_id,
    aws_secret_access_key,
    region,
    service
)

# OpenSearch 终端节点
host = 'vpc-xxx.us-east-1.es.amazonaws.com'
url = f'https://{host}/_snapshot/target-snapshot-repository?pretty'

# 请求负载
payload = {
    "type": "s3",
    "settings": {
        "bucket": "target-bucket",
        "region": "us-east-1",
        "role_arn": "arn-of-role-for-putting-on-oss"
    }
}

try:
    # 发送请求（同时使用 AWS 签名和 Basic Auth）
    response = requests.put(
        url,
        auth=awsauth,  # AWS 签名认证
        headers={
            'Content-Type': 'application/json'
        },
        json=payload,
        verify=False  # 生产环境应使用有效证书
    )
    
    print(f'HTTP 状态码: {response.status_code}')
    print('响应内容:')
    print(response.text)

except requests.exceptions.RequestException as e:
    print(f'请求失败: {str(e)}')