-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathportcheck.py
89 lines (79 loc) · 2.36 KB
/
portcheck.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import sys, json
try:
import boto3
from botocore.exceptions import ClientError
except ImportError:
sys.exit("Could not import 'boto3', please install this package.")
# first and only argument is the security group id
#if (len(sys.argv) != 2):
# sys.exit("USAGE: python ipme.py [security-group-id]")
#else:
# group_id = str(sys.argv[1])
# set up client object
client = boto3.client('ec2')
# find security group by that id
try:
response = client.describe_security_groups(
Filters=[
# only concerned with ssh
{
'Name': 'ip-permission.from-port',
'Values': ['22']
},
{
'Name': 'ip-permission.cidr',
'Values': ['0.0.0.0/0', '0.0.0.0', '0.0.0.0/*']
},
{
'Name': 'ip-permission.protocol',
'Values': ['tcp']
},
],
# GroupIds=[
# group_id,
# ],
DryRun=False
)
# throw error or exception, whatever comes first
except ClientError as e:
sys.exit(e)
except Exception as ex:
sys.exit(ex)
# finally, update the security group to authorize ingress traffic over 22 (SSH) from this device's external ip
else:
if response['SecurityGroups']:
print(response)
# used to print informative message
info = response['SecurityGroups'][0]
# used later in this script
old_access = response['SecurityGroups'][0]['IpPermissions'][0]
print('Found security group (id={0[GroupId]}) named {0[GroupName]}'.format(info))
else:
sys.exit('Nothing found matching that criteria (SSH rule).')
#try:
# first revoke ingress for old ip,
# data = client.revoke_security_group_ingress(
# GroupId=group_id,
# IpPermissions=[
# old_access
# ]
# )
# then authorize ingress for new one
# data = client.authorize_security_group_ingress(
# GroupId=group_id,
# IpPermissions=[
# {
# 'IpProtocol': 'tcp',
# 'FromPort': 22,
# 'ToPort': 22,
# 'IpRanges': [{'CidrIp': ext_ip}]
# }
# ]
# )
# throw error or exception, whatever comes first
#except ClientError as e:
# sys.exit(e)
#except Exception as ex:
# sys.exit(ex)
#else:
# print('Ingress Successfully Set %s' % data)