阿里云 Python SDK (以安全组为例)

前言

最开始想法是随时控制 ECS 的出入规则,就是快速的开启端口,关闭端口等,每次登陆网页修改太麻烦了,所有就找到了API,然后开始用 JAVA 写,写完了怎么运行都不对,说签名不完整。即将崩溃的时候发现了 SDK,正高兴呢,发现没有 jar 包,而是 maven 的,我又不会,然后就搞了 Python 的 SDK,就酱紫。

示例代码

首先需要安装SDK
1
pip install aliyun-python-sdk-ecs

SDK列表和帮助见此处阿里云Python SDK
代码如下:

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
#!/usr/bin/env python2
# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeSecurityGroupAttributeRequest
from aliyunsdkecs.request.v20140526 import RevokeSecurityGroupRequest
from aliyunsdkecs.request.v20140526 import AuthorizeSecurityGroupRequest

def describeSecurityGroupAttributeRequest():
"""查询安全组规则
"""
request = DescribeSecurityGroupAttributeRequest.DescribeSecurityGroupAttributeRequest()
request.set_SecurityGroupId('sg-2872p4xdv')
request.set_accept_format('json')
return request

def revokeSecurityGroupRequest():
"""撤销安全组规则
"""
request = RevokeSecurityGroupRequest.RevokeSecurityGroupRequest()
request.set_SecurityGroupId('sg-2872p4xdv')
request.set_IpProtocol('all')
request.set_PortRange('-1/-1')
request.set_SourceCidrIp('0.0.0.0/0')
request.set_Policy('accept')
request.set_accept_format('json')
return request

def authorizeSecurityGroupRequest():
"""授权安全组规则
"""
request = AuthorizeSecurityGroupRequest.AuthorizeSecurityGroupRequest()
request.set_SecurityGroupId('sg-2872p4xdv')
request.set_IpProtocol('all')
request.set_PortRange('-1/-1')
request.set_SourceCidrIp('0.0.0.0/0')
request.set_Policy('accept')
request.set_accept_format('json')
return request

if __name__ == '__main__':
clt = client.AcsClient('AccessKeyId','AccessKeySecret','cn-qingdao')
request = revokeSecurityGroupRequest()
# request = authorizeSecurityGroupRequest()
# request = describeSecurityGroupAttributeRequest()
result = clt.do_action(request)
print(result)

相关链接

云服务器 ECS > API 文档 > 简介
aliyun-openapi-python-sdk
阿里云Python SDK

如果你不是非常有钱,请不要捐赠,土豪随意