介绍:

1.aws安全组策略:协议、端口、流入流量、流出流量
2.aws 控制python库: boto3,需先安装。
3.脚本作用:获取本地外网IP-----》添加到指定安全组

代码:

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

import re
import urllib2
import datetime
import boto3
from botocore.exceptions import ClientError

def get_ip():
        # 获取外网IP
    url = 'https://www.ipip.net/'
    html = urllib2.urlopen(url).read()
    ips = re.findall('\d+\.\d+\.\d+\.\d+',html)
    ips = list(set(ips))
    ip = ''
    for item in ips:
        if item != '8.8.8.8':
            ip = item
            break
    return ip

d_port = 11230                                 # 目标端口
group_id = 'sg-xxxxxxx'                    # 要操作的安全组id
client = boto3.client('ec2',
    region_name='ap-south-1',         # 安全组所属区域
    aws_access_key_id='xxxxxxxxxxx',                   #IAM账号id
    aws_secret_access_key='xxxxxxxxxxx')           #IAM账号key

now = datetime.datetime.now().strftime('%m-%d_%H:%M:%S')

my_ip =  get_ip()
if my_ip is not None:
    my_ip = my_ip + "/32"
# print my_ip

r_ip = []
res = client.describe_security_groups(GroupIds=[group_id])
for item in res['SecurityGroups'][0]['IpPermissions']:
    if item['FromPort'] == d_port:
        for iprange in item['IpRanges']:
            r_ip.append(iprange['CidrIp'])
# print r_ip

if my_ip not in r_ip:
    try:
        data = client.authorize_security_group_ingress(
            GroupId = group_id,
            IpPermissions=[{
            'IpProtocol': 'tcp',
            'FromPort':d_port,
            'ToPort':d_port,
            'IpRanges':[{'CidrIp':my_ip,'Description':now}]
            }]
            )
        print "Add %s successful..."%my_ip
    except ClientError as e:
        print e