删除租户下unbound的外网port

随便记录一下好了

#!/usr/bin/env python
####################################
#Input: host, user_name and password
#Output: Delete Unbond Port
####################################
import subprocess
import json

keystone_port = '5000'
neutron_port = '9696'
content_type = '-H "Content-type: application/json"'
accept = '-H "Accept: application/json"'

#Modify by yourself
host = ''
user_name = ''
password = ''
tenant_name = 'Project_%s' %user_name

def Pipe(cmd):
    try:
        proc = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
        return proc.communicate()[0]
    except Exception, e:
        print('Execute failed, command: %s, error: %s' %(cmd, str(e)))
        return None

def System(cmd):
    try:
        s = subprocess.Popen(cmd, shell = True, stdout = None)
        s.wait()
    except Exception, e:
        print('Execute failed, command: %s, error: %s' %(cmd, str(e)))
        return None

class HTTPRESTful(object):
    ''' HTTP API, curl '''
    def __init__(self):
        print('Now, more public ports for us, congratulations ~!')

    def get_tenant_id_and_token(self):
        ''' get tenant_id and token '''
        keystone_url = 'http://%s:%s/v2.0/tokens' %(host, keystone_port)
        keystone_body = '{"auth": {"tenantName": "%s", "passwordCredentials": {"username": "%s", "password": "%s"}}}' %(tenant_name, user_name, password)
        cmd = "curl -s -X POST %s %s %s -d \'%s\'" %(keystone_url, content_type, accept, keystone_body)
        token_get = json.loads(Pipe(cmd))
        self.token = token_get['access']['token']['id']
        self.tenant_id = token_get['access']['token']['tenant']['id']

    def get_and_delete_unbond_port(self):
        ''' get all unbond public port '''
        neutron_url = 'http://%s:%s/v2.0/ports?vnetwork=public&tenant_id=%s' %(host, neutron_port, self.tenant_id)
        x_auth_token = '-H "X-Auth-Token: %s"' %self.token
        cmd = "curl -s -X GET \'%s\' %s %s" %(neutron_url, accept, x_auth_token)
        port_list = json.loads(Pipe(cmd))['ports']
        print 'Delete Unbond Port From: %s' %user_name
        print '========================================================================'
        for port in port_list:
            if len(port['device_id']) == 0:
                print 'Delete Unbond Port: %s' %(port['id'])
                self.delete_port(port['id'])
        print '========================================================================'

    def delete_port(self, port_id):
        ''' delete port '''
        neutron_url = 'http://%s:%s/v2.0/ports/%s' %(host, neutron_port, port_id)
        x_auth_token = '-H "X-Auth-Token: %s"' %self.token
        cmd = 'curl -s -X DELETE %s %s' %(neutron_url, x_auth_token)
        System(cmd)

if __name__ == '__main__':
    restful = HTTPRESTful()
    restful.get_tenant_id_and_token()
    restful.get_and_delete_unbond_port()

 

发表评论