Advertisement
Guest User

Untitled

a guest
May 25th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.04 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import sys, os, stat, re, subprocess, getopt, json
  4. #regions={'eu-west-3':'vpc-xxxxx'}
  5.  
  6. def makesg(profile, sgid, vpcid, source, dest, shell):
  7. try:
  8. os.mkdir(vpcid);
  9. except FileExistsError as e:
  10. pass
  11.  
  12. script = open('{0}/{1}.sh'.format(vpcid, sgid), 'w')
  13.  
  14. cmd = [ 'aws', 'ec2', 'describe-security-groups', '--region=%s' % source, '--output=json', ]
  15. if source:
  16. cmd.append("--group-id=%s" % (sgid))
  17. else:
  18. cmd = [ 'aws', 'ec2', 'describe-security-groups', '--group-id=%s' % sgid, '--output=json', ]
  19.  
  20. if profile:
  21. cmd.append('--profile')
  22. cmd.append(profile)
  23.  
  24. ap = subprocess.check_output(cmd)
  25.  
  26. data = json.loads(ap.decode('utf-8'))
  27.  
  28. if 'SecurityGroups' not in data:
  29. print("Internal error: no SecurityGroups key in data")
  30. sys.exit(3)
  31. sg1 = data['SecurityGroups'][0]
  32. groupName = sg1['GroupName'] #+ '_migrated'
  33. groupDesc = sg1['Description']
  34.  
  35. # Sanity check
  36. for ipp in sg1['IpPermissions']:
  37. if 'FromPort' not in ipp: continue
  38. if 'IpProtocol' not in ipp: continue
  39. if 'IpRanges' not in ipp: continue
  40. if 'ToPort' not in ipp: continue
  41. if len(ipp['UserIdGroupPairs']) > 0:
  42. sys.stderr.write("Warning: ignoring User Id info\n")
  43. #for ipr in ipp['IpRanges']:
  44. #for k in ipr.keys():
  45. #if k != 'CidrIp':
  46. #sys.stderr.write("Error: Don't know how to handle")
  47. #sys.stderr.write("key %s in IpRanges\n" % (k))
  48. #sys.exit(4)
  49. for ipp in sg1['IpPermissionsEgress']:
  50. if 'FromPort' not in ipp: continue
  51. if 'IpProtocol' not in ipp: continue
  52. if 'IpRanges' not in ipp: continue
  53. if 'ToPort' not in ipp: continue
  54. if len(ipp['UserIdGroupPairs']) > 0:
  55. sys.stderr.write("Warning: ignoring User Id info\n")
  56. #for ipr in ipp['IpRanges']:
  57. #for k in ipr.keys():
  58. #if k != 'CidrIp':
  59. #sys.stderr.write("Error: Don't know how to handle")
  60. #sys.stderr.write("key %s in IpRanges\n" % (k))
  61. #sys.exit(4)
  62.  
  63. # if dest:
  64. # cmd = "aws ec2 describe-vpcs"
  65. # if shell:
  66. # print("vpcout=(`%s --region '%s' --output text`)" % (cmd, dest))
  67. # else:
  68. # print("%s --region '%s' --output text" % (cmd, dest))
  69. # print('VPCID=$vpcout', file=script)
  70. destinations = dest
  71.  
  72. if shell:
  73. print("# Commands auto-generated by the copysg.py script", file=script)
  74. print(" ", file=script)
  75. if dest is None:
  76. #destinations = regions
  77. print("No destination VPC")
  78. sys.exit(1)
  79. for dest,vpc in destinations.items():
  80. cmd.append("--filters=Name=group-name,Values='%s'" % (groupName))
  81. ap = subprocess.check_output(cmd)
  82.  
  83. if ap is not None:
  84. delete_cmd = "aws ec2 delete-security-group"
  85. create_cmd = "aws ec2 create-security-group --vpc-id=%s" % (vpc)
  86. if shell:
  87. #if ap is not None:
  88. #print("sgout=(`%s --group-name='%s' --region %s --output table`)" % (delete_cmd, groupName, dest), file=script)
  89. #print('if [ $? != 0 ]; then', file=script)
  90. #print(' echo "Error: %s failed"' % (delete_cmd), file=script)
  91. #print(' exit 1', file=script)
  92. #print('fi', file=script)
  93. print("sgout=(`%s --group-name='%s' --region %s --description='%s' --output table`)" % (create_cmd, groupName, dest, groupDesc), file=script)
  94. print('if [ $? != 0 ]; then', file=script)
  95. print(' echo "Error: %s failed"' % (create_cmd), file=script)
  96. print(' exit 1', file=script)
  97. print('fi', file=script)
  98. print('if [ "${sgout[6]}" != \'GroupId\' ]; then', file=script)
  99. print(' echo "Error: expected \'GroupId\', got ${sgout[6]}"', file=script)
  100. print(' exit 1', file=script)
  101. print('fi', file=script)
  102. print('SGID=${sgout[8]}', file=script)
  103. print("""while true
  104. do
  105. describeinstance_output="$(aws ec2 describe-security-groups --group-ids $SGID --region {0} --output json)"
  106. retval=$?
  107. if [ $retval -eq 0 ]
  108. then
  109. break
  110. fi
  111.  
  112. echo "Waiting for Security Group $SGID Creation..."
  113. sleep 1
  114. done
  115. """.format(dest), file=script)
  116. else:
  117. print("%s --group-name='%s' --region %s" % (delete_cmd, groupName, dest), file=script)
  118. print("%s --group-name='%s' --region %s --description='%s'" % (create_cmd, groupName, dest, groupDesc), file=script)
  119.  
  120. for ipp in sg1['IpPermissions']:
  121. #from pprint import pprint
  122. #pprint(ipp)
  123. #if 'FromPort' not in ipp: continue
  124. #if 'IpProtocol' not in ipp: continue
  125. #if 'IpRanges' not in ipp: continue
  126. #if 'ToPort' not in ipp: continue
  127. for ipr in ipp['IpRanges']:
  128. cidr = ipr['CidrIp']
  129. #cidr6 = ipr['CidrIpv6']
  130.  
  131. auth_cmd = "aws ec2 authorize-security-group-ingress"
  132. if shell:
  133. print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']),end=" ", file=script)
  134. else:
  135. print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']),end=" ", file=script)
  136. if 'ToPort' in ipp and ipp['ToPort'] < 0:
  137. # ICMP ToPort was -1 ???
  138. ipp['ToPort'] = ipp['FromPort']
  139. if 'FromPort' in ipp and ipp['FromPort'] != ipp['ToPort']:
  140. print("--port=%s-%s" % (ipp['FromPort'], ipp['ToPort']),end=" ", file=script)
  141. else:
  142. if 'FromPort' in ipp:
  143. print("--port=%s" % (ipp['FromPort']),end=" ", file=script)
  144. print("--cidr=%s" % (ipr['CidrIp']), file=script)
  145. #print("--cidr=%s" % (ipr['CidrIpv6']), file=script)
  146. if shell:
  147. print('if [ $? != 0 ]; then', file=script)
  148. print(' echo "Error: %s failed"' % (auth_cmd), file=script)
  149. print(' exit 1', file=script)
  150. print('fi', file=script)
  151.  
  152. for ipp in sg1['IpPermissionsEgress']:
  153. #if 'FromPort' not in ipp: continue
  154. #if 'IpProtocol' not in ipp: continue
  155. #if 'IpRanges' not in ipp: continue
  156. #if 'ToPort' not in ipp: continue
  157. for ipr in ipp['IpRanges']:
  158. cidr = ipr['CidrIp']
  159.  
  160. auth_cmd = "aws ec2 authorize-security-group-egress"
  161. if shell:
  162. print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']), end=" ", file=script)
  163. else:
  164. print("%s --region %s --group-id=$SGID --protocol='%s'" % (auth_cmd, dest, ipp['IpProtocol']), end=" ", file=script)
  165. if 'ToPort' in ipp and ipp['ToPort'] < 0:
  166. # ICMP ToPort was -1 ???
  167. ipp['ToPort'] = ipp['FromPort']
  168. if 'FromPort' in ipp and ipp['FromPort'] != ipp['ToPort']:
  169. print("--port=%s-%s" % (ipp['FromPort'], ipp['ToPort']),end=" ", file=script)
  170. else:
  171. if 'FromPort' in ipp:
  172. print("--port=%s" % (ipp['FromPort']),end=" ", file=script)
  173. print("--cidr=%s" % (ipr['CidrIp']), file=script)
  174. if shell:
  175. print('if [ $? != 0 ]; then', file=script)
  176. print(' echo "Error: %s failed. But I will continue."' % (auth_cmd), file=script)
  177. #print(' exit 1', file=script)
  178. print('fi', file=script)
  179.  
  180. if 'Tags' in sg1:
  181. for tag in sg1['Tags']:
  182. if 'Key' in tag and tag['Key'] == 'Name':
  183. if shell:
  184. print("aws ec2 create-tags --resources $SGID --region {0}".format(dest),end=" ", file=script)
  185. print('--tags "Key=Name,Value=%s"' % (tag['Value']), file=script)
  186. else:
  187. print("aws ec2 create-tags --resources $SGID",end=" ", file=script)
  188. print('--tags "Key=Name,Value=%s"' % (tag['Value']), file=script)
  189.  
  190. #setting script permissions
  191. os.chmod(script.name, 0o755)
  192.  
  193.  
  194. ############################### MAIN #######################################
  195.  
  196.  
  197. def main():
  198. try:
  199. opts, args = getopt.getopt(sys.argv[1:], "hp:sv:", [ "help", "profile=", "shell", "vpc=", "src=", "dest=", ])
  200. except getopt.GetoptError:
  201. usage()
  202. sys.exit(2)
  203.  
  204. profile = None
  205. vpcid = None
  206. shell = False
  207. source = None
  208. destination = None
  209. sourcevpc = "vpc-0661d760" #todo: later add an option in command line
  210.  
  211. for o,a in opts:
  212. if o in ("-h", "--help"):
  213. usage()
  214. return
  215. if o in ("-p", "--profile"):
  216. profile = a
  217. if o in ("-s", "--shell"):
  218. shell = True
  219. if o in ("-sc", "--src"):
  220. source = a
  221. if o in ("-ds", "--dest"):
  222. destination = a
  223. if o in ("-v", "--vpc"):
  224. vpcid = a
  225.  
  226. destination = {destination:vpcid}
  227.  
  228. # if len(args) != 1:
  229. # print("ERROR: You must give a security group id")
  230. # usage()
  231. # sys.exit(1)
  232. sgid = args[0]
  233.  
  234. #get all sg's in my vpc
  235. cmd = [ 'aws', 'ec2', 'describe-security-groups', '--region=%s' % source, '--filters', 'Name=vpc-id,Values=%s' % sourcevpc, '--output=json', ]
  236. print(cmd)
  237. cmd_output = subprocess.check_output(cmd) #runs command
  238. parsed_cmd_output = json.loads(cmd_output.decode('utf-8')) #parses output of command
  239.  
  240. if 'SecurityGroups' not in parsed_cmd_output:
  241. print("Unable to get list of security groups for source vpc.")
  242. sys.exit(3)
  243.  
  244. #below is a test
  245. makesg(profile, sgid, vpcid, source, destination, shell)
  246.  
  247. #run on all SG's found in VPC
  248. # for sg in parsed_cmd_output['SecurityGroups']:
  249. # sgid = sg['GroupId']
  250. # print("Working on {0}".format(sgid))
  251. # makesg(profile, sgid, vpcid, source, destination, shell)
  252.  
  253. def usage():
  254. print("copysg.py [-h] [--profile=alt_profile] [--shell] [--vpc=vpcid] [-src=source_region] [--dest=dest_region]", end=" ")
  255. print("sg_id")
  256. print(" -h - help")
  257. print(" --profile (or -p) - use alternate aws cli profile")
  258. print(" --shell (or -s) - wrap commands in shell syntax to capture id")
  259. print(" --vpc (or -v) - specify destination VPC ID for new SG")
  260. print(" --src (or -sc) - specify source region for new SG")
  261. print(" --dest (or -ds) - specify destination region for new SG")
  262.  
  263. if __name__ == "__main__":
  264. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement