获取具有公共Ip的每个网络接口的安全组规则

2024-09-27 00:19:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在尝试用Boto3获取一些信息时遇到了麻烦。 我想做的是:

我在AWS帐户中遍历所有的网络接口,如果一个接口正在使用并且它有一个公共IP,我会得到它的安全组,看看是否有任何规则开放到internet上,比如0.0.0.0/0或公共IP。目标是要有一个关于所有连接到internet的网络接口实例的安全报告。在

脚本如下:

# create dict
ip = {}
SGName = ''
SGID = ''
interfaceID = ''
ListGroups = {}
Message = 'Instances With Public Ips :'  
 # check aws profiles
for p in awsProfile:
    print(p)
    # define aws session
    session = Session(region_name="eu-west-1", profile_name=p)
    ec2 = session.resource('ec2')
    client = session.client('ec2')
    all_interfaces = ec2.network_interfaces.all()
    for interface in all_interfaces:
        interfaceID = interface.id
        desc = client.describe_network_interfaces(NetworkInterfaceIds=[interfaceID])
        for d in desc['NetworkInterfaces']:
            if interface.status == 'in-use' and d.get('Association') is not None:
                interfaceID = interface.id
                print(interfaceID)
                desc = client.describe_network_interfaces(NetworkInterfaceIds=[interfaceID])
                publicIp = d.get('Association')['PublicIp']
                SGName = d.get('Groups')[0].get('GroupName')
                SGID = d.get('Groups')[0].get('GroupId')
                ListGroups[SGName] = SGID
                Message = Message + str(p)+str(interface.vpc.id)+str(interface.attachment.get('InstanceId'))+str(interface.description)+str(interface.private_ip_address)+str(publicIp)+str(interfaceID)+str(SGID)+str(SGName)
                for key in ListGroups:
                    sg = ec2.SecurityGroup(ListGroups[key])
                    for i in range(len(sg.ip_permissions)):
                        for j in range(len(sg.ip_permissions[i]['IpRanges'])):
                            ip = IPNetwork(sg.ip_permissions[i]['IpRanges'][j]['CidrIp'])
                            if(ip.is_private()==False):
                                Message = Message + 'Public Securiy Groups details :'
                                Message = Message +str(ListGroups[key])+str(sg.ip_permissions[i]['ToPort'])

当我执行脚本时,会出现以下错误:

^{pr2}$

它说某个安全组不存在。我应该得到连接到某个网络接口的安全组ID,并且它存在。我跟踪了网络接口,发现了这个错误,它有2个安全组,其中任何一个在错误中都没有这个ID。你知道怎么用这个吗?在


Tags: inipmessageforgetsgec2interfaces
1条回答
网友
1楼 · 发布于 2024-09-27 00:19:09

如果您的唯一任务是查找可能构成安全威胁的安全组,请转到AWS Trusted Advisor。其核心检查之一是安全组的检查:

Checks security groups for rules that allow unrestricted access (0.0.0.0/0) to specific ports. Unrestricted access increases opportunities for malicious activity (hacking, denial-of-service attacks, loss of data). The ports with highest risk are flagged red, and those with less risk are flagged yellow. Ports flagged green are typically used by applications that require unrestricted access, such as HTTP and SMTP.

相关问题 更多 >

    热门问题