Ejemplo n.º 1
0
def createSG(ec2, name, rules):
    """
	Create a new SecurityGroup
	"""
    # check if the security group exists
    group = None
    sgGroups = [sg for sg in ec2.get_all_security_groups() if sg.name == name]
    if sgGroups:
        group = sgGroups[0]
        ec2.delete_security_group(name=name, group_id=group)
    print "Creating %s Security Group" % name
    group = ec2.create_security_group(name, 'group for %s' % name)
    if group:
        # Set the inbound rules
        for rule in rules:
            if rule.src_group_name:
                group.authorize(ip_protocol=rule.ip_protocol,
                                from_port=rule.from_port,
                                to_port=rule.to_port,
                                cidr_ip=rule.cidr_ip,
                                src_group=group)
            else:
                group.authorize(ip_protocol=rule.ip_protocol,
                                from_port=rule.from_port,
                                to_port=rule.to_port,
                                cidr_ip=rule.cidr_ip,
                                src_group=None)
        return True
    else:
        logError('Error during ' + name + ' Security Group update')
        return False
Ejemplo n.º 2
0
def terminate(elastic_IP):
    global allocation_id

    ec2 = boto3.client('ec2')
    conn = boto.ec2.connect_to_region("us-east-1")

    filters = {"ip-address": elastic_IP}
    instances = conn.get_only_instances(filters=filters)

    filters = [{'Name': 'public-ip', 'Values': [elastic_IP]}]

    addresses = ec2.describe_addresses(Filters=filters)

    inst_id = str(instances[0].id)
    alloc_id = addresses['Addresses'][0]['AllocationId']

    ec2.release_address(AllocationId=alloc_id)
    conn.terminate_instances(instance_ids=[
        inst_id,
    ])

    while instances[0].update(
    ) != "terminated":  #wait until the instance has been terminated
        time.sleep(5)

    ec2.delete_security_group(GroupName='csc326-group23')
    ec2.delete_key_pair(KeyName='key')
Ejemplo n.º 3
0
def security_group_ssh():

	# If the demo security group exists, purge so it's known to be clean.
	groups = ec2.get_all_security_groups()
	for group in groups:
		if group.name == DEMO_SECURITY_GROUP:
			ec2.delete_security_group(DEMO_SECURITY_GROUP)

	# create new security group opening up ssh and tomcat7 ports
	group = ec2.create_security_group(DEMO_SECURITY_GROUP, 'Security group for demonstration')
	my_cidr = get_external_ip() + '/32'
	group.authorize('tcp', 22, 22, my_cidr)
	group.authorize('tcp', 8080, 8080, my_cidr)
	return;
Ejemplo n.º 4
0
    def delete_security_group(self, group_name):
        if self.account.vpc_id:
            try:
                sg = self.account.security_groups.get(name=group_name)
                kwargs = {'group_id': sg.group_id}
            except ObjectDoesNotExist:
                return
        else:
            kwargs = {'name': group_name}

        ec2 = self.connect_ec2()
        try:
            ec2.delete_security_group(**kwargs)
        except boto.exception.EC2ResponseError as e:
            logger.error('Error deleting security group {0}'.format(group_name))
            raise DeleteGroupException(e.error_message)
Ejemplo n.º 5
0
    def delete_security_group(self, group_name):
        if self.account.vpc_id:
            try:
                sg = self.account.security_groups.get(name=group_name)
                kwargs = {'group_id': sg.group_id}
            except ObjectDoesNotExist:
                return
        else:
            kwargs = {'name': group_name}

        ec2 = self.connect_ec2()
        try:
            ec2.delete_security_group(**kwargs)
        except boto.exception.EC2ResponseError as e:
            logger.error(
                'Error deleting security group {0}'.format(group_name))
            raise DeleteGroupException(e.error_message)
Ejemplo n.º 6
0
    def delete_security_group(self, group_name):
        from django.core.exceptions import ObjectDoesNotExist

        if self.obj.vpc_id:
            try:
                sg = self.obj.security_groups.get(name=group_name)
                kwargs = {'group_id': sg.group_id}
            except ObjectDoesNotExist:
                return
        else:
            kwargs = {'name': group_name}

        ec2 = self.connect_ec2()
        try:
            ec2.delete_security_group(**kwargs)
        except boto.exception.EC2ResponseError, e:
            logger.exception('Error deleting security group {0}'.format(
                group_name)
            )
            if e.status == 400:
                raise BadRequest(e.error_message)
            raise InternalServerError(e.error_message)
Ejemplo n.º 7
0
def createSG(ec2,name,rules):
	"""
	Create a new SecurityGroup
	"""
	# check if the security group exists
	group = None
	sgGroups = [sg for sg in ec2.get_all_security_groups() if sg.name == name]
	if sgGroups:
		group = sgGroups[0]
		ec2.delete_security_group(name=name, group_id=group)	
	print "Creating %s Security Group" % name
	group = ec2.create_security_group(name, 'group for %s' % name)
	if group:
		# Set the inbound rules
		for rule in rules:
			if rule.src_group_name:
				group.authorize(ip_protocol=rule.ip_protocol,from_port=rule.from_port,to_port=rule.to_port,cidr_ip=rule.cidr_ip,src_group=group)
			else:
				group.authorize(ip_protocol=rule.ip_protocol,from_port=rule.from_port,to_port=rule.to_port,cidr_ip=rule.cidr_ip,src_group=None)
		return True
	else:
		logError('Error during '+name+' Security Group update')
		return False
Ejemplo n.º 8
0
# get_all_security_groups
print "get_all_security_groups"

import boto.ec2
print "begin delete security group"

ec2 = boto.ec2.connect_to_region(region,
                                 aws_access_key_id=aws_access_key,
                                 aws_secret_access_key=aws_secret_key)
sgroup = ec2.get_all_security_groups()
for i in sgroup:
    print i.id
    print i.name
    if i.name != 'default':
        try:
            ec2.delete_security_group(i.id)
        except Exception, e:
            pass
print "peering_connections"
orgtab = vpcCon.get_all_vpc_peering_connections()
for i in orgtab:
    print i.id
    print vpcCon.delete_vpc_peering_connection(i.id)

#print "route"
print "route table"
orgtab = vpcCon.get_all_route_tables()
for i in orgtab:
    print i.id
    print vpcCon.delete_route_table(i.id)
Ejemplo n.º 9
0
log = logging.getLogger('botocross')
bc.configure_logging(log, args.log_level)
credentials = bc.parse_credentials(args)
regions = bc.filter_regions(boto.ec2.regions(), args.region)

# execute business logic
groupname = args.name if args.name else ""
group_id = args.id if args.id else ""
log.info("Deleting EC2 security groups '" + groupname + group_id + "':")

groupnames = [args.name] if args.name else None
group_ids = [args.id] if args.id else None

for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        groups = ec2.get_all_security_groups(groupnames=groupnames,
                                             group_ids=group_ids)
        for group in groups:
            num_instances = " with " + str(len(
                group.instances())) + " instances assigned" if len(
                    group.instances()) else ""
            if group.instances() and not args.force:
                print 'NOT deleting security group ' + group.name + "(" + group.id + ")" + num_instances + " (use --force to override)"
            else:
                print 'Deleting security group ' + group.name + "(" + group.id + ")" + num_instances
                ec2.delete_security_group(name=args.name, group_id=args.id)
    except boto.exception.BotoServerError, e:
        log.error(e.error_message)
def isSelected(region):
    return True if region.name.find(args.region) != -1 else False

# execute business logic
groupname = args.name if args.name else ""
group_id = args.id if args.id else ""
heading = "Deleting EC2 security groups '" + groupname + group_id + "'"
regions = boto.ec2.regions()
if args.region:
    heading += " (filtered by region '" + args.region + "')"
    regions = filter(isSelected, regions)

groupnames = [args.name] if args.name else None
group_ids = [args.id] if args.id else None

print heading + ":"
for region in regions:
    pprint(region.name, indent=2)
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        groups = ec2.get_all_security_groups(groupnames=groupnames, group_ids=group_ids)
        for group in groups:
            num_instances = " with " + str(len(group.instances())) + " instances assigned" if len(group.instances()) else ""
            if group.instances() and not args.force:
                print 'NOT deleting security group ' + group.name + "(" + group.id + ")" + num_instances + " (use --force to override)"
            else:
                print 'Deleting security group ' + group.name + "(" + group.id + ")" + num_instances
                ec2.delete_security_group(name=args.name, group_id=args.id)
    except boto.exception.BotoServerError, e:
        print e.error_message
Ejemplo n.º 11
0
    print vpcCon.delete_internet_gateway(i.id)    

# get_all_security_groups
print "get_all_security_groups"

import boto.ec2
print "begin delete security group"

ec2 = boto.ec2.connect_to_region(region, aws_access_key_id= aws_access_key, aws_secret_access_key =aws_secret_key)
sgroup = ec2.get_all_security_groups()
for i in sgroup:
    print i.id
    print i.name
    if i.name != 'default':
        try:
            ec2.delete_security_group(i.id)
        except Exception, e:
            pass
print "peering_connections"    
orgtab = vpcCon.get_all_vpc_peering_connections()
for i in orgtab:
    print i.id
    print vpcCon.delete_vpc_peering_connection(i.id)  

#print "route"
print "route table"
orgtab = vpcCon.get_all_route_tables()
for i in orgtab:
    print i.id
    print vpcCon.delete_route_table(i.id)    
    
enis = ec2.get_all_network_interfaces()
for eni in enis:
    for eni_grp in eni.groups:
        if eni_grp.name not in groups_in_use:
            groups_in_use.append(eni_grp.name)

delete_candidates = []
for group in allgroups:
    if group not in groups_in_use and not group.startswith('AWS-OpsWorks-'):
        delete_candidates.append(group)

if args.delete:
    print "We will now delete security groups identified to not be in use."
    for group in delete_candidates:
        ec2.delete_security_group(group)
else:
    print "The list of security groups to be removed is below."
    print "Run this again with `-d` to remove them"
    #pp.pprint(sorted(delete_candidates))
    for group in sorted(delete_candidates):
        print "   " + group

print "---------------"
print "Activity Report"
print "---------------"

print "Total number of Security Groups evaluated: %d" % (len(groups_in_use))
print "Total number of EC2 Instances evaluated: %d" % (len(reservations))
print "Total number of Load Balancers evaluated: %d" % (len(load_balancers))
print "Total number of RDS instances evaluated: %d" % (len(dbs))
Ejemplo n.º 13
0
enis = ec2.get_all_network_interfaces()
for eni in enis:
    for eni_grp in eni.groups:
      if eni_grp.name not in groups_in_use:
        groups_in_use.append(eni_grp.name)

delete_candidates = []
for group in allgroups:
    if group not in groups_in_use and not group.startswith('AWS-OpsWorks-'):
        delete_candidates.append(group)

if args.delete:
    print "We will now delete security groups identified to not be in use."
    for group in delete_candidates:
        ec2.delete_security_group(group)
else:
    print "The list of security groups to be removed is below."
    print "Run this again with `-d` to remove them"
    #pp.pprint(sorted(delete_candidates))
    for group in sorted(delete_candidates):
        print "   " + group

print "---------------"
print "Activity Report"
print "---------------"

print "Total number of Security Groups evaluated: %d" % (len(groups_in_use))
print "Total number of EC2 Instances evaluated: %d" % (len(reservations))
print "Total number of Load Balancers evaluated: %d" % (len(load_balancers))
print "Total number of RDS instances evaluated: %d" % (len(dbs))