我在尝试使用Boto3获取某些信息时遇到了麻烦。 以下是我想要做的:获得每个网络接口的安全组规则与公共Ip
我循环遍历AWS账户中的所有网络接口,如果一个接口正在使用中并且它有一个公共IP,我得到它的安全组并查看是否有任何规则打开像0.0.0.0/0或公共IP一样流向互联网。目标是针对网络接口连接到互联网的所有实例提供安全报告。
下面是脚本:
# 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'])
当我执行脚本我得到这个错误:
Traceback (most recent call last):
File "openNetwork.py", line 62, in <module>
for i in range(len(sg.ip_permissions)):
File "C:\Python\Python35-32\lib\site-packages\boto3\resources\factory.py", line 339, in property_loader
self.load()
File "C:\Python\Python35-32\lib\site-packages\boto3\resources\factory.py", line 505, in do_action
response = action(self, *args, **kwargs)
File "C:\Python\Python35-32\lib\site-packages\boto3\resources\action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
File "C:\Python\Python35-32\lib\site-packages\botocore\client.py", line 310, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\Python\Python35-32\lib\site-packages\botocore\client.py", line 599, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'sg-9abc52e3' d
oes not exist
它说,一些安全组不存在。我应该获得连接到某个网络接口并存在的安全组ID。我跟踪了导致该错误的网络接口,并且它有2个安全组,他们中的任何一个在错误中都没有这个ID。任何想法如何让这个工作?