阿里云ecs安全组自动更新白名单

  • 内容
  • 评论
  • 相关

因服务器安全原因,进放行指定ip访问,阿里云安全管控有一个白名单,但是需要手动配置并且生效时间太长,所以这里用安全组配置。

每次ip变动时执行下脚本即可,再或者要求全部自动自动化,只需要监听下网络变化,执行脚本就即可,这里ip变化不频繁,手动执行即可满足要求,脚本如下,运行环境 Python 2

#!/usr/bin/env python
#coding=utf-8

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.AuthorizeSecurityGroupRequest import AuthorizeSecurityGroupRequest
from aliyunsdkecs.request.v20140526.RevokeSecurityGroupRequest import RevokeSecurityGroupRequest
from urllib2 import urlopen
import os

#需要esc服务器权限
sk1 = 'AccessKey ID'
sk2 = 'AccessKey Secret'
groupid = 'sg-2881n92zq'
ip = urlopen('http://ip.42.pl/raw').read()
print 'IP:', ip
    
client = AcsClient(sk1, sk2, 'cn-qingdao')

#需要放行的端口
portlist = ['1234/1234','1235/1235','9999/9999']

for portitem in portlist:
    request = AuthorizeSecurityGroupRequest()
    request.set_accept_format('json')

    request.set_SecurityGroupId(groupid)
    request.set_IpProtocol("tcp")
    request.set_PortRange(portitem)
    request.set_SourceCidrIp(ip)
    # request.set_SourcePortRange(portitem)
    response = client.do_action_with_exception(request)
    # python2:  print(response) 
    print(response)

fname = "ip.dat"
fileprt = os.path.isfile(fname)

if fileprt:

    fo = open(fname, "r+")
    str = fo.read(100)
    if ip != str:
        print "删除旧的策略组"
        print "原IP : ", str
        for portitem in portlist:
            request = AuthorizeSecurityGroupRequest()
            request.set_accept_format('json')


            request = RevokeSecurityGroupRequest()
            request.set_accept_format('json')

            request.set_SecurityGroupId(groupid)
            request.set_PortRange(portitem)
            request.set_IpProtocol("tcp")
            request.set_SourceCidrIp(str)
            request.set_SourcePortRange(portitem)
            response = client.do_action_with_exception(request)
            print(response)
    fo.close()

    fo = open(fname, "w+")
    fo.write(ip)
    # 关闭打开的文件
    fo.close()


else:
    fo = open(fname, "w+")
    fo.write(ip)
    # 关闭打开的文件
    fo.close()

第一次用需要安装下阿里云的库

pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-ecs

评论

0条评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注