前置条件
- 拥有可以操作
AuthorizeSecurityGroup
API 的AccessKey
前往 AccessKey 管理 添加 accessKey。
添加一个子账号,创建 AccessKey
给该 AccessKey 授权一个最小的权限:AuthorizeSecurityGroup
,只能添加安全组的入方向规则。
准备好了 AccessKey,就可以开始准备脚本了。
以下提供两种方式, Python 、Golang(推荐,因为编译后看不到密码)。
代码实现:添加一条安全组入规则,支持本机IP访问 22 端口,如果希望放开所有端口,可以将 request.PortRange 的值修改为 1/65535
1. Python
1.1 安装依赖包
pip3 install aliyun-python-sdk-ecs==4.24.3
1.2 编写脚本
请替换代码中的 <accessKeyId>, <accessSecret>, <YourSecurityGroupId>
, <RegionId>
.
#!/usr/bin/env python#coding=utf-8importrequestsfromaliyunsdkcore.clientimportAcsClientfromaliyunsdkcore.acs_exception.exceptionsimportClientExceptionfromaliyunsdkcore.acs_exception.exceptionsimportServerExceptionfromaliyunsdkecs.request.v20140526.AuthorizeSecurityGroupRequestimportAuthorizeSecurityGroupRequestr=requests.get('https://ipw.cn/api/ip/myip') clientIP=r.text# <accessKeyId>, <accessSecret>: 前往 https://ram.console.aliyun.com/manage/ak 添加 accessKey# RegionId:安全组所属地域ID ,比如 `cn-guangzhou`# 访问 [DescribeRegions:查询可以使用的阿里云地域](https://next.api.aliyun.com/api/Ecs/2014-05-26/DescribeRegions) 查阅# 国内一般是去掉 ECS 所在可用区的后缀,比如去掉 cn-guangzhou-b 的尾号 -bclient=AcsClient('<accessKeyId>', '<accessSecret>', '<RegionId>') request=AuthorizeSecurityGroupRequest() request.set_accept_format('json') request.set_SecurityGroupId("<YourSecurityGroupId>") # 安全组IDrequest.set_IpProtocol("tcp") # 协议,可选 tcp,udp, icmp, gre, all:支持所有协议request.set_PortRange("22/22") # 端口范围,使用斜线(/)隔开起始端口和终止端口,如果信任所有端口为 1/65535request.set_Priority("1") # 安全组规则优先级,数字越小,代表优先级越高。取值范围:1~100request.set_Policy("accept") # accept:接受访问, drop: 拒绝访问request.set_NicType("internet") # internet:公网网卡, intranet:内网网卡。request.set_SourceCidrIp(clientIP) # 源端IPv4 CIDR地址段。支持CIDR格式和IPv4格式的IP地址范围。response=client.do_action_with_exception(request) # python2: print(response) print(str(response, encoding='utf-8')) print("Client IP: %s was successfully added to the Security Group."%clientIP)
1.3 执行代码
$ python3 addSecurityGroupRule.py {"RequestId":"1657CAC5-8B1F-4EB8-A947-DC76F44B27C8"} Client IP: 119.xx.xx.xx was successfully added to the Security Group.
2. Golang
2.1 安装依赖包
$ goget github.com/aliyun/alibaba-cloud-sdk-go/services/ecs
2.2 编写脚本
请替换代码中的 <accessKeyId>, <accessSecret>, <YourSecurityGroupId>
, <RegionId>
.
packagemainimport ( "fmt""io/ioutil""net/http""github.com/aliyun/alibaba-cloud-sdk-go/services/ecs") funcmain() { responseClient, errClient :=http.Get("https://ipw.cn/api/ip/myip") // 获取外网 IPiferrClient!=nil { fmt.Printf("获取外网 IP 失败,请检查网络\n") panic(errClient) } // 程序在使用完 response 后必须关闭 response 的主体。deferresponseClient.Body.Close() body, _ :=ioutil.ReadAll(responseClient.Body) clientIP :=string(body) // <accessKeyId>, <accessSecret>: 前往 https://ram.console.aliyun.com/manage/ak 添加 accessKey// RegionId:安全组所属地域ID ,比如 `cn-guangzhou`// 访问 [DescribeRegions:查询可以使用的阿里云地域](https://next.api.aliyun.com/api/Ecs/2014-05-26/DescribeRegions) 查阅// 国内一般是去掉 ECS 所在可用区的后缀,比如去掉 cn-guangzhou-b 的尾号 -bclient, err :=ecs.NewClientWithAccessKey("<RegionId>", "<accessKeyId>", "<accessSecret>") iferr!=nil { fmt.Print(err.Error()) } request :=ecs.CreateAuthorizeSecurityGroupRequest() request.Scheme="https"request.SecurityGroupId="<YourSecurityGroupId>"// 安全组IDrequest.IpProtocol="tcp"// 协议,可选 tcp,udp, icmp, gre, all:支持所有协议request.PortRange="22/22"// 端口范围,使用斜线(/)隔开起始端口和终止端口request.Priority="1"// 安全组规则优先级,数字越小,代表优先级越高。取值范围:1~100request.Policy="accept"// accept:接受访问, drop: 拒绝访问request.NicType="internet"// internet:公网网卡, intranet:内网网卡。request.SourceCidrIp=clientIP// 源端IPv4 CIDR地址段。支持CIDR格式和IPv4格式的IP地址范围。response, err :=client.AuthorizeSecurityGroup(request) iferr!=nil { fmt.Print(err.Error()) } fmt.Printf("Response: %#v\nClient IP: %s was successfully added to the Security Group.\n", response, clientIP) }
2.3 执行代码
$ go run addSecurityGroupRule.go Response: &ecs.AuthorizeSecurityGroupResponse{BaseResponse:(*responses.BaseResponse)(0xc00014c080), RequestId:"53C16A7C-91DC-48E6-B6BA-B0830A00C7C1"} Client IP: 119.xx.xx.xx was successfully added to the Security Group.
无误后,编译程序
$ go build addSecurityGroupRule.go $ ./addSecurityGroupRule Response: &ecs.AuthorizeSecurityGroupResponse{BaseResponse:(*responses.BaseResponse)(0xc0002c0080), RequestId:"BEAC369E-2267-4EEF-9463-26A1DEA3ED9B"} Client IP: 119.xx.xx.xx was successfully added to the Security Group.
自动化可以解放我们,一起加油吧。
Reference
- [1] aliyun. 增加一条入方向安全组规则
- [2] IP 查询. 获取客户端公网 IP 地址