浏览代码

First release of FindSecurityGroup

Fred Damstra 9 年之前
父节点
当前提交
6b0e995a8e
共有 3 个文件被更改,包括 187 次插入0 次删除
  1. 1 0
      .gitignore
  2. 70 0
      FindSecurityGroup.py
  3. 116 0
      FindSecurityGroupInProfile.py

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+.*.swp

+ 70 - 0
FindSecurityGroup.py

@@ -0,0 +1,70 @@
+#! /usr/bin/python
+#
+# Find a security group amongst all profile configured. Note that it makes multiple calls
+# to the FindSecurityGroupInProfile.py in parallel.
+#
+# Unbuffered, no CRLF print:
+from __future__ import print_function
+import re, sys, os, subprocess
+import boto3
+import boto3.session
+import threading 	# We may not do it yet, but developing with threadsafe in mind, as best I can
+
+try:
+	# Python 3
+	import builtins
+except ImportError:
+	# Python 2
+	import __builtin__ as builtins
+
+# Debug levels:
+#	1 = Show progress
+#	2 = Informational
+# 	5 = Include boto3 logging
+DEBUG=0
+
+if len(sys.argv) != 2:
+	print("Usage: " + os.path.basename(sys.argv[0]) + " <searchstring>")
+	exit(1)
+
+SEARCHSTRING=sys.argv[1]
+
+# Load profiles
+try:
+	cfile = open(os.path.expanduser("~") + "/.aws/credentials", "r")
+except:
+	print("You must have a ~/.aws/credentials file with profiles configured.")
+	exit(3)
+
+profiles = set()
+for line in cfile:
+	profile = re.match('^\[(.+)\]', line)
+	if(profile):
+		profiles.add(profile.group(1))
+
+# End of for line
+FOUND=0
+processes = set()
+for profile in profiles:
+	if DEBUG >= 2:
+		print("Searching profile " + profile)
+	process = subprocess.Popen(['FindSecurityGroupInProfile.py', SEARCHSTRING, profile])
+	if DEBUG >= 2:
+		print("PID = " + str(process.pid))
+	processes.add(process)
+# We should have spawned all child processes. Let's wait for them.
+
+for process in processes:
+	if DEBUG >= 2:
+		print("Waiting on process " + str(process.pid))
+	returncode = process.wait()
+	if(returncode == 0):
+		# Found one
+		FOUND = FOUND + 1
+
+# Searched all the profiles
+if(FOUND > 0):
+	exit(0)
+exit(255)
+
+

+ 116 - 0
FindSecurityGroupInProfile.py

@@ -0,0 +1,116 @@
+#! /usr/bin/python
+#
+# Find an instance within a profile, across all regions
+#
+# Unbuffered, no CRLF print:
+from __future__ import print_function
+import sys, os
+import boto3
+import boto3.session
+import botocore
+import threading 	# We may not do it yet, but developing with threadsafe in mind, as best I can
+
+try:
+	# Python 3
+	import builtins
+except ImportError:
+	# Python 2
+	import __builtin__ as builtins
+
+# Debug levels:
+#	1 = Show progress
+#	2 = Informational
+# 	3 = Additional error info (includes failed lookups)
+# 	5 = Include boto3 logging
+DEBUG=0
+
+# Fancy print function to make it 3.4 compatible:
+if len(sys.argv) != 3:
+	print("Usage: " + os.path.basename(sys.argv[0]) + "<searchstring> <profile>")
+	exit(1)
+
+if DEBUG >= 5:
+	boto3.set_stream_logger('botocore', level=DEBUG)
+
+SEARCHSTRING=sys.argv[1]
+PROFILE=sys.argv[2]
+
+# Set the profile to use
+try:
+	boto3.setup_default_session(profile_name=PROFILE)
+except:
+	print("Could not find profile: " + PROFILE)
+	exit(2)
+
+# Connect to ec2
+ec2 = boto3.client('ec2')
+
+# Grab list of regions
+regions = set()
+for region in ec2.describe_regions()['Regions']:
+	regions.add(region['RegionName'])
+
+# For each array, let's search:
+FOUND=0
+FOUNDSTR=""
+if DEBUG == 1:
+	print("Searching.", end="")
+	sys.stdout.flush()
+for region in regions:
+	if DEBUG == 1:
+		print(".", end="")
+		sys.stdout.flush()
+	if DEBUG >= 2:
+		print("Searching region " + region + " in profile " + PROFILE)
+	ec2 = boto3.client('ec2', region_name=region)
+	try:
+		sg = ec2.describe_security_groups(GroupIds=[ SEARCHSTRING ])
+		FOUND=FOUND+1
+		if DEBUG >= 2:
+			print("FOUND in profile '" + PROFILE + "', Region: '" + region + "': ID=" + str(sg['SecurityGroups'][0]['GroupId']))
+		if FOUND > 1:
+			FOUNDSTR = FOUNDSTR + "\n"
+		FOUNDSTR = FOUNDSTR + "FOUND in profile '" + PROFILE + "', Region: '" + region
+		continue
+	except botocore.exceptions.ClientError as e:
+		if DEBUG >= 2:
+			print("Not found by ID in profile '" + PROFILE + "', Region: '" + region + "'")
+	except:
+		if DEBUG >= 3:
+			# Print the error
+			print(str( sys.exc_info() ))
+	try:
+		sg = ec2.describe_security_groups(Filters=[ {'Name': 'group-name', 'Values': [ SEARCHSTRING ] } ])
+	except:
+		if DEBUG >= 3:
+			# Print the error
+			print(str( sys.exc_info() ))
+	try:
+		if(sg['SecurityGroups'][0]['GroupId']):
+			FOUND=FOUND+1
+			if DEBUG >= 2:
+				print("FOUND in profile '" + PROFILE + "', Region: '" + region + "': ID=" + str(sg['SecurityGroups'][0]['GroupId']))
+			if FOUND > 1:
+				FOUNDSTR = FOUNDSTR + "\n"
+			FOUNDSTR = FOUNDSTR + "FOUND in profile '" + PROFILE + "', Region: '" + region
+			continue
+	except IndexError:
+		if DEBUG >= 2:
+			print("Not found by Name search in profile '" + PROFILE + "', Region: '" + region + "'")
+
+# End of for region	
+if DEBUG == 1:
+	print(".")
+	sys.stdout.flush()
+
+if DEBUG >= 2:
+	print("Found " + str(FOUND) + " instances.")
+
+if FOUND > 0:
+	print(FOUNDSTR)
+	exit(0)
+else:
+	if DEBUG == 1:
+		print("Not found.")
+	exit(255)
+