我正在尝试使用Python和BOTO3列出AWS中所有设备的IP(ELB,EC2等)
我已经能够提取整个库存但是我如何承担一个角色并仅列出所有链接的AWS账户中的IP和设备?
迟到的答案,但希望它有帮助。您应该使用network_interfaces
来获取所有服务的IP地址。我使用一组命名的配置文件运行类似的报告。像这样的东西:
for profile in self.profiles:
print(f'Analyzing {profile}...')
session = boto3.Session(profile_name=profile)
ec2 = session.resource('ec2')
for eni in ec2.network_interfaces.all():
attachment_info = 'No attachment'
if eni.attachment:
if 'InstanceId' in eni.attachment:
attachment_info = eni.attachment['InstanceId']
else:
attachment_info = eni.attachment['InstanceOwnerId']
row = (
profile,
eni.private_ip_address,
eni.subnet_id,
eni.subnet.cidr_block,
attachment_info,
)
print(row)
关于帐户中的角色,正如您在代码中看到的那样,boto3将遵循~/.aws/config
中的命名配置文件。见https://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html
但是,您也可以通过以下代码直接在代码中承担角色:
sts = boto3.client('sts')
creds = sts.assume_role(
RoleArn=f'arn:aws:iam::{acct_id}:role/{role_name}',
RoleSessionName='...'
)
auth = {
'aws_access_key_id': creds['Credentials']['AccessKeyId'],
'aws_secret_access_key': creds['Credentials']['SecretAccessKey'],
'aws_session_token': creds['Credentials']['SessionToken'],
}
session = boto3.Session(**auth)
ec2 = session.resource('ec2')
例如,如果您还需要遍历多个区域,这可能是更可取的。
对于EC2,可以轻松收集私有/公共IP地址,如下所示:
EC2 — Boto 3 Docs 1.7.30 documentation
import boto3
ec2 = boto3.resource(service_name='ec2',
region_name='xxx',
aws_access_key_id='xxx',
aws_secret_access_key='xxx')
for i in ec2.instances.all():
print(i.private_ip_address)
print(i.public_ip_address)
但是,您需要为EC2使用iam密钥。