Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import sys, os, stat, re, subprocess, getopt, json
- #regions={'eu-west-3':'vpc-xxxxx'}
- def makesg(profile, sgid, vpcid, source, dest, shell):
- try:
- os.mkdir(vpcid);
- except FileExistsError as e:
- pass
- script = open('{0}/{1}.sh'.format(vpcid, sgid), 'w')
- cmd = [ 'aws', 'ec2', 'describe-security-groups', '--region=%s' % source, '--output=json', ]
- if source:
- cmd.append("--group-id=%s" % (sgid))
- else:
- cmd = [ 'aws', 'ec2', 'describe-security-groups', '--group-id=%s' % sgid, '--output=json', ]
- if profile:
- cmd.append('--profile')
- cmd.append(profile)
- ap = subprocess.check_output(cmd)
- data = json.loads(ap.decode('utf-8'))
- if 'SecurityGroups' not in data:
- print("Internal error: no SecurityGroups key in data")
- sys.exit(3)
- sg1 = data['SecurityGroups'][0]
- groupName = sg1['GroupName'] #+ '_migrated'
- groupDesc = sg1['Description']
- # Sanity check
- for ipp in sg1['IpPermissions']:
- if 'FromPort' not in ipp: continue
- if 'IpProtocol' not in ipp: continue
- if 'IpRanges' not in ipp: continue
- if 'ToPort' not in ipp: continue
- if len(ipp['UserIdGroupPairs']) > 0:
- sys.stderr.write("Warning: ignoring User Id info\n")
- #for ipr in ipp['IpRanges']:
- #for k in ipr.keys():
- #if k != 'CidrIp':
- #sys.stderr.write("Error: Don't know how to handle")
- #sys.stderr.write("key %s in IpRanges\n" % (k))
- #sys.exit(4)
- for ipp in sg1['IpPermissionsEgress']:
- if 'FromPort' not in ipp: continue
- if 'IpProtocol' not in ipp: continue
- if 'IpRanges' not in ipp: continue
- if 'ToPort' not in ipp: continue
- if len(ipp['UserIdGroupPairs']) > 0:
- sys.stderr.write("Warning: ignoring User Id info\n")
- #for ipr in ipp['IpRanges']:
- #for k in ipr.keys():
- #if k != 'CidrIp':
- #sys.stderr.write("Error: Don't know how to handle")
- #sys.stderr.write("key %s in IpRanges\n" % (k))
- #sys.exit(4)
- # if dest:
- # cmd = "aws ec2 describe-vpcs"
- # if shell:
- # print("vpcout=(`%s --region '%s' --output text`)" % (cmd, dest))
- # else:
- # print("%s --region '%s' --output text" % (cmd, dest))
- # print('VPCID=$vpcout', file=script)
- destinations = dest
- if shell:
- print("# Commands auto-generated by the copysg.py script", file=script)
- print(" ", file=script)
- if dest is None:
- #destinations = regions
- print("No destination VPC")
- sys.exit(1)
- for dest,vpc in destinations.items():
- cmd.append("--filters=Name=group-name,Values='%s'" % (groupName))
- ap = subprocess.check_output(cmd)
- if ap is not None:
- delete_cmd = "aws ec2 delete-security-group"
- create_cmd = "aws ec2 create-security-group --vpc-id=%s" % (vpc)
- if shell:
- #if ap is not None:
- #print("sgout=(`%s --group-name='%s' --region %s --output table`)" % (delete_cmd, groupName, dest), file=script)
- #print('if [ $? != 0 ]; then', file=script)
- #print(' echo "Error: %s failed"' % (delete_cmd), file=script)
- #print(' exit 1', file=script)
- #print('fi', file=script)
- print("sgout=(`%s --group-name='%s' --region %s --description='%s' --output table`)" % (create_cmd, groupName, dest, groupDesc), file=script)
- print('if [ $? != 0 ]; then', file=script)
- print(' echo "Error: %s failed"' % (create_cmd), file=script)
- print(' exit 1', file=script)
- print('fi', file=script)
- print('if [ "${sgout[6]}" != \'GroupId\' ]; then', file=script)
- print(' echo "Error: expected \'GroupId\', got ${sgout[6]}"', file=script)
- print(' exit 1', file=script)
- print('fi', file=script)
- print('SGID=${sgout[8]}', file=script)
- print("""while true
- do
- describeinstance_output="$(aws ec2 describe-security-groups --group-ids $SGID --region {0} --output json)"
- retval=$?
- if [ $retval -eq 0 ]
- then
- break
- fi
- echo "Waiting for Security Group $SGID Creation..."
- sleep 1
- done
- """.format(dest), file=script)
- else:
- print("%s --group-name='%s' --region %s" % (delete_cmd, groupName, dest), file=script)
- print("%s --group-name='%s' --region %s --description='%s'" % (create_cmd, groupName, dest, groupDesc), file=script)
- for ipp in sg1['IpPermissions']:
- #from pprint import pprint
- #pprint(ipp)
- #if 'FromPort' not in ipp: continue
- #if 'IpProtocol' not in ipp: continue
- #if 'IpRanges' not in ipp: continue
- #if 'ToPort' not in ipp: continue
- for ipr in ipp['IpRanges']:
- cidr = ipr['CidrIp']
- #cidr6 = ipr['CidrIpv6']
- auth_cmd = "aws ec2 authorize-security-group-ingress"
- if shell:
- print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']),end=" ", file=script)
- else:
- print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']),end=" ", file=script)
- if 'ToPort' in ipp and ipp['ToPort'] < 0:
- # ICMP ToPort was -1 ???
- ipp['ToPort'] = ipp['FromPort']
- if 'FromPort' in ipp and ipp['FromPort'] != ipp['ToPort']:
- print("--port=%s-%s" % (ipp['FromPort'], ipp['ToPort']),end=" ", file=script)
- else:
- if 'FromPort' in ipp:
- print("--port=%s" % (ipp['FromPort']),end=" ", file=script)
- print("--cidr=%s" % (ipr['CidrIp']), file=script)
- #print("--cidr=%s" % (ipr['CidrIpv6']), file=script)
- if shell:
- print('if [ $? != 0 ]; then', file=script)
- print(' echo "Error: %s failed"' % (auth_cmd), file=script)
- print(' exit 1', file=script)
- print('fi', file=script)
- for ipp in sg1['IpPermissionsEgress']:
- #if 'FromPort' not in ipp: continue
- #if 'IpProtocol' not in ipp: continue
- #if 'IpRanges' not in ipp: continue
- #if 'ToPort' not in ipp: continue
- for ipr in ipp['IpRanges']:
- cidr = ipr['CidrIp']
- auth_cmd = "aws ec2 authorize-security-group-egress"
- if shell:
- print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']), end=" ", file=script)
- else:
- print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']), end=" ", file=script)
- if 'ToPort' in ipp and ipp['ToPort'] < 0:
- # ICMP ToPort was -1 ???
- ipp['ToPort'] = ipp['FromPort']
- if 'FromPort' in ipp and ipp['FromPort'] != ipp['ToPort']:
- print("--port=%s-%s" % (ipp['FromPort'], ipp['ToPort']),end=" ", file=script)
- else:
- if 'FromPort' in ipp:
- print("--port=%s" % (ipp['FromPort']),end=" ", file=script)
- print("--cidr=%s" % (ipr['CidrIp']), file=script)
- if shell:
- print('if [ $? != 0 ]; then', file=script)
- print(' echo "Error: %s failed. But I will continue."' % (auth_cmd), file=script)
- #print(' exit 1', file=script)
- print('fi', file=script)
- if 'Tags' in sg1:
- for tag in sg1['Tags']:
- if 'Key' in tag and tag['Key'] == 'Name':
- if shell:
- print("aws ec2 create-tags --resources $SGID --region {0}".format(dest),end=" ", file=script)
- print('--tags "Key=Name,Value=%s"' % (tag['Value']), file=script)
- else:
- print("aws ec2 create-tags --resources $SGID",end=" ", file=script)
- print('--tags "Key=Name,Value=%s"' % (tag['Value']), file=script)
- #setting script permissions
- os.chmod(script.name, 0o755)
- ############################### MAIN #######################################
- def main():
- try:
- opts, args = getopt.getopt(sys.argv[1:], "hp:sv:", [ "help", "profile=", "shell", "vpc=", "src=", "dest=", ])
- except getopt.GetoptError:
- usage()
- sys.exit(2)
- profile = None
- vpcid = None
- shell = False
- source = None
- destination = None
- sourcevpc = "vpc-0661d760" #todo: later add an option in command line
- for o,a in opts:
- if o in ("-h", "--help"):
- usage()
- return
- if o in ("-p", "--profile"):
- profile = a
- if o in ("-s", "--shell"):
- shell = True
- if o in ("-sc", "--src"):
- source = a
- if o in ("-ds", "--dest"):
- destination = a
- if o in ("-v", "--vpc"):
- vpcid = a
- destination = {destination:vpcid}
- # if len(args) != 1:
- # print("ERROR: You must give a security group id")
- # usage()
- # sys.exit(1)
- sgid = args[0]
- #get all sg's in my vpc
- cmd = [ 'aws', 'ec2', 'describe-security-groups', '--region=%s' % source, '--filters', 'Name=vpc-id,Values=%s' % sourcevpc, '--output=json', ]
- print(cmd)
- cmd_output = subprocess.check_output(cmd) #runs command
- parsed_cmd_output = json.loads(cmd_output.decode('utf-8')) #parses output of command
- if 'SecurityGroups' not in parsed_cmd_output:
- print("Unable to get list of security groups for source vpc.")
- sys.exit(3)
- #below is a test
- makesg(profile, sgid, vpcid, source, destination, shell)
- #run on all SG's found in VPC
- # for sg in parsed_cmd_output['SecurityGroups']:
- # sgid = sg['GroupId']
- # print("Working on {0}".format(sgid))
- # makesg(profile, sgid, vpcid, source, destination, shell)
- def usage():
- print("copysg.py [-h] [--profile=alt_profile] [--shell] [--vpc=vpcid] [-src=source_region] [--dest=dest_region]", end=" ")
- print("sg_id")
- print(" -h - help")
- print(" --profile (or -p) - use alternate aws cli profile")
- print(" --shell (or -s) - wrap commands in shell syntax to capture id")
- print(" --vpc (or -v) - specify destination VPC ID for new SG")
- print(" --src (or -sc) - specify source region for new SG")
- print(" --dest (or -ds) - specify destination region for new SG")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement