Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Boto从ENIs添加或删除安全组?_Python_Amazon Web Services_Boto - Fatal编程技术网

Python 如何使用Boto从ENIs添加或删除安全组?

Python 如何使用Boto从ENIs添加或删除安全组?,python,amazon-web-services,boto,Python,Amazon Web Services,Boto,我正在使用Python接口来管理我的EC2软件定义的网络,我正在编写一种方法来管理弹性网络接口(ENIs)上的安全组 我不知道如何告诉EC2在ENI中添加或删除安全组 到目前为止,我的方法基本上是: import boto conn = boto.connect_ec2() my_eni = conn.get_all_network_interfaces(['eni-xxxx1234'])[0] my_eni_groups = my_eni.groups my_eni_sg_ids = [ x

我正在使用Python接口来管理我的EC2软件定义的网络,我正在编写一种方法来管理弹性网络接口(ENIs)上的安全组

我不知道如何告诉EC2在ENI中添加或删除安全组

到目前为止,我的方法基本上是:

import boto
conn = boto.connect_ec2()

my_eni = conn.get_all_network_interfaces(['eni-xxxx1234'])[0]
my_eni_groups = my_eni.groups
my_eni_sg_ids = [ x.id for x in my_eni_groups ]

desired_sg_state = ['sg-xxxx1234','sg-xxxx5678']

# if present, do nothing, else, add it somehow..
for sg in desired_sg_state:
    if sg in my_eni_sg_ids:
        print('Okay: ', sg)
    else:
        # not sure what method to use here!

我搜索了文档,在
boto.ec2.securitygroup
boto.ec2.networkinterface
对象中找不到任何有关安全组关联/解除关联的信息。我确信有一种方法可以做到这一点,但这对我来说并不明显。

相关操作是在级别上的--您可以使用该级别更改弹性网络接口上的安全组:

import boto

sg_string_list = ['sg-xxxx1234', 'sg-xxxx5678']

conn = boto.connect_ec2()
conn.modify_network_interface_attribute(interface_id=eni_id,
                                        attr='groupSet',
                                        value=sg_string_list)
其中广义形式为:
修改网络接口属性(接口id、属性、值、附件id=None、干运行=False)

重要的是要记住,您指定的是希望ENI处于的状态,而不是使用
modify\u network\u interface\u属性
调用简单地添加/删除SGs;如果需要添加行为,请首先获取当前SG列表,然后附加新SG:

import boto
conn = boto.connect_ec2()

my_eni_groups = conn.get_all_network_interfaces(['eni-1582af5d'])[0].groups
my_eni_sg_ids = [ x.id for x in my_eni_groups ]

add_sg = 'sg-xxxx1234'

if add_sg not in my_eni_sg_ids:
    my_eni_sg_ids.append(add_sg)

    #only need to call this if we modified the list
    conn.modify_network_interface_attribute(interface_id=eni_id,
                                            attr='groupSet',
                                            value=my_eni_sg_ids)

和之间没有一对一的请求参数映射,因此请确保在Boto文档中或通过(请注意,您可能需要更改分支以匹配您的版本(以及可能是链接的行号))。

一个样式问题,但在Python中,我们通常缩进4个空格P好的,你修好了,再加上一个