0
点赞
收藏
分享

微信扫一扫

使用Python自动修改AWS安全组规则允许当前电脑访问

豆丁趣 2022-03-19 阅读 56

背景介绍

AWS云服务安全的最佳实践是为AWS中的EC2实例配置最小范围的安全组访问范围, 所以通常会设置仅允许某些来自互联网的IP地址访问, 但是家里的宽带会经常更换公网IP, 从家里访问实例每次都要手工修改安全组的规则, 很不方便, 还是那句话: 人生苦短, 我用Python, 下面搞起来~

实现代码

代码逻辑很简单, 主要就两步:

  1. 获取当前电脑的互联网IP
  2. 修改指定的安全组规则
import requests
from datetime import datetime
import boto3
from botocore.exceptions import ClientError

# 获取本机当前的公网IP
myIP = requests.get('http://checkip.amazonaws.com/').content.strip().decode('utf8')

# 修改指定安全组规则
client = boto3.client('ec2')
sg_group_id = 'sg-0f7bb2c37631dbaa5'    # 修改为自己安全组的ID
sg_rule_id = 'sgr-0ee92e0e1583e0eaf'    # 修改为自己安全组中某条规则的ID
try:
    response = client.modify_security_group_rules(
        GroupId=sg_group_id,
        SecurityGroupRules=[
            {
                'SecurityGroupRuleId': sg_rule_id,
                'SecurityGroupRule': {
                    'IpProtocol': 'tcp',
                    'FromPort': 0,
                    'ToPort': 65535,
                    'CidrIpv4': f'{myIP}/32',
                    'Description': datetime.now().strftime('%Y-%m-%d %H:%M:%S')    # 描述信息使用当前的时间
                }
            }
        ]
    )

    print(response)
except ClientError as e:
    print(e)

文件保存在C:\Users\lpwm\Documents\update_aws_sg_rule.py

配置开机自动运行

将上面的代码保存到本地磁盘中后, 需要先创建一个PowerShell脚本保存在C:\Users\lpwm\Documents\update_aws_sg_rule.ps1

python "C:\Users\lpwm\Documents\update_aws_sg_rule.py"

用下面PowerShell命令创建计划任务, 让系统每次启动的时候都执行这个批处理文件更新安全组规则

PS C:\Users\lpwm> $trigger = New-JobTrigger -AtStartup
PS C:\Users\lpwm> Register-ScheduledJob -Trigger $trigger -FilePath C:\Users\lpwm\Documents\update_aws_sg_rule.ps1 -Name Update_AWS_SG_Rule

Id         Name            JobTriggers     Command                                  Enabled
--         ----            -----------     -------                                  -------
1          Update_AWS_S... 1               C:\Users\lpwm\Documents\update_aws_sg... True

重启一下检查任务是否正确执行

PS C:\Users\lpwm> Get-Job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Update_AWS_S... PSScheduledJob  Completed     False           localhost            python "C:\Users\lpwm\...

同时登陆EC2控制台检查安全组规则, 确认备注信息中的时间与当前一致, Nice~

举报

相关推荐

0 条评论