python批量给云主机配置安全组

python批量给云主机配置安全组

用公有云的思路去思考去实现一个安全稳定、可伸缩和经济的业务构架,云运维是有别与传统运维的,比如说了解公有云的都知道安全组的概念,安全组跟防火墙功能很相似,那我的机器是要设置iptables还是要设置安全组呢?设置了安全组还要设置iptables吗?他们有什么区别?我相信很多人对这些有些困惑,以我个人经验(因为我接触亚马逊后就再也没有给云主机配置过iptables了),我给的建议是如果可以用安全组就不用iptables来管理机器,因为它们有本质的区别:

第一,安全组是在宿主上面的拦截,iptables是在系统层面的拦截,也就是说如果有人想攻击你,你采用的是安全组方式,这个攻击包根本就到不了你机器上。

第二,配置iptables是项复杂的工程,如果稍有不慎,后果是毁灭性的,我猜测有过2年运维经验小伙伴应该有把自己关在主机外面的经历,如果采用安全组这方面是可控的,即使有问题,你基本上也可以快速恢复。

第三,iptables是在每台服务器上写大量的重复规则,而且不可以分层去管理这些规则,安全组是按层来管理机器的安全配置,只需调整你需要改动的部分就可以实现批量去管理机器。

ok,概念就介绍到这里,接下来我们要上干货了,因为给几百台机器配置不同的安全组也是个大工程,如果你在控制台去操作,我想你会疯掉,所以这就说到如何去批量管理和操作这些安全组,这里用到了公有云提供的API,因为公有云j基本都有自己的API接口,所以调用他们的API来实现一些自动化操作我认为是每个使用公有云来构架自己业务的运维必须要学会的,今天我就分享下如何批量给大量机器添加和移除安全组,脚本本身是在qcloudcli的基础上封装了一层,脚本如下:

#!/usr/bin/env python

# -*- coding:utf-8 -*- 

import subprocess

import json

import sys

扫描二维码关注公众号,回复: 963530 查看本文章

import argparse

def R(s):

    return "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))

def get_present_sgid(vmid):

    descmd = '/usr/bin/qcloudcli dfw  DescribeSecurityGroups --instanceId ' + vmid.strip()

    p = subprocess.Popen(descmd, shell=True, stdout=subprocess.PIPE)  

    output = p.communicate()[0]

    res = json.loads(output)

    sgid = []

    for d in res['data']:

        sid = d['sgId']

        sgid.append(str(sid))

    return sgid

def make_json(vmid,sgid):

    pdata = {}

    pdata["instanceId"] = vmid

    pdata["sgIds"] = sgid

    pjson = json.dumps(pdata)

    return pjson

def add_sgid(vmfile,newsid):

    fi = open(vmfile)

    for v in fi:

        v = v.strip()

        res = get_present_sgid(v)

        print res

        res.append(newsid)

        pjson = make_json(v,res)

        modcmd = 'qcloudcli dfw ModifySecurityGroupsOfInstance --instanceSet ' + "'[" + pjson+ "]'"

        p = subprocess.Popen(modcmd, shell=True, stdout=subprocess.PIPE)

        output = p.communicate()[0]

        print output

def remove_sgid(vmfile,newsid):

    fi = open(vmfile)

    for v in fi:

        v = v.strip()

        res = get_present_sgid(v)

        res.remove(newsid)

        pjson = make_json(v,res)

        modcmd = 'qcloudcli dfw ModifySecurityGroupsOfInstance --instanceSet ' + "'[" + pjson+ "]'"

        p = subprocess.Popen(modcmd, shell=True, stdout=subprocess.PIPE)

        output = p.communicate()[0]

        #print output

if __name__ == "__main__":

    parser=argparse.ArgumentParser(description='change sgid', usage='%(prog)s [options]')

    parser.add_argument('-f','--file', nargs='?', dest='filehost', help='vmidfile')

    parser.add_argument('-g','--sgid', nargs='?', dest='sgid', help='sgid')

    parser.add_argument('-m','--method', nargs='?', dest='method', help='Methods only support to add or remove')

    if len(sys.argv)==1:

        parser.print_help()

    else:

        args=parser.parse_args()

        if args.filehost is not None and args.sgid is not None and args.method is not None:

            if args.method == 'add':

                add_sgid(args.filehost, args.sgid)

            elif args.method == 'remove':

                remove_sgid(args.filehost, args.sgid)

            else:

                print R('Methods only support to add or remove')

        else:

            print R('Error format, please see the usage:')

            parser.print_help()

这个脚本支持批量增加和删除某个安全组,-f后面接一个文件,写入实例的id的列表,-g后面是要增加和删除的安全组Id,-m后面支持add 和remove操作,就是增加或删除,脚本整体思路是先找出实例的安全组列表,然后将新的安全组Id在列表中加入或移除

猜你喜欢

转载自www.cnblogs.com/xuaijun/p/9065683.html