diff --git a/aws/aws-config-status.sh b/aws/aws-config-status.sh new file mode 100755 index 0000000..167e296 --- /dev/null +++ b/aws/aws-config-status.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +# Check config recorder status in all regions + +aws --region=us-east-1 ec2 describe-regions --query Regions[].RegionName --output text | sed -e 's/\t/\n/g' | while read r; do +echo "$r" +echo "Recorder on: $(aws --region $r configservice describe-configuration-recorder-status --query ConfigurationRecordersStatus[].recording --output text)" +echo "Recording global resources: $(aws --region $r configservice describe-configuration-recorders --query ConfigurationRecorders[].recordingGroup.includeGlobalResourceTypes --output text)" +done diff --git a/aws/aws-endpoint-inventory.sh b/aws/aws-endpoint-inventory.sh new file mode 100755 index 0000000..1d30668 --- /dev/null +++ b/aws/aws-endpoint-inventory.sh @@ -0,0 +1,3 @@ +#!/bin/bash +aws ec2 describe-regions --query Regions[].RegionName --output text | tr '\t' '\n' | parallel \ +aws ec2 --region {} describe-vpc-endpoints --query VpcEndpoints[].ServiceName --output text | tr '\t' '\n' | sort | uniq -c diff --git a/aws/gzip-file.py b/aws/gzip-file.py new file mode 100755 index 0000000..cbd8948 --- /dev/null +++ b/aws/gzip-file.py @@ -0,0 +1,8 @@ +#!/usr/bin/python3 +import gzip +import shutil + +with open('test.txt', 'rb') as f_in: + with gzip.open('test.gz', 'wb') as f_out: + shutil.copyfileobj(f_in, f_out) + diff --git a/aws/iam-user-audit.sh b/aws/iam-user-audit.sh new file mode 100755 index 0000000..d7ede72 --- /dev/null +++ b/aws/iam-user-audit.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +AID=$(aws sts get-caller-identity --query Account --output text) + +# dump list of user to temp file +aws iam list-users | jq -cr '.Users[] | [.UserName, .PasswordLastUsed // "NoPassword"] | @csv' > /tmp/iusers.txt + +cat /tmp/iusers.txt | while read line; do + USER=$(echo $line | awk -F, '{print $1}' | tr -d \") + PLU=$(grep "$USER\"," /tmp/iusers.txt | awk -F, '{print $2}' | awk -FT '{print $1}' | tr -d \") + echo "$AID, $USER, $PLU, NA, NA" + aws iam list-access-keys --user-name $USER --query AccessKeyMetadata[].AccessKeyId --output text | tr '\t' '\n' | while read k; do + echo "$AID, $USER, NA, $k, $(aws iam get-access-key-last-used --access-key-id $k --query AccessKeyLastUsed.LastUsedDate | awk -FT '{print $1}' | tr -d \")" + done +done diff --git a/aws/s3-file-email.py b/aws/s3-file-email.py new file mode 100644 index 0000000..994172e --- /dev/null +++ b/aws/s3-file-email.py @@ -0,0 +1,50 @@ +import os.path +import boto3 +import gzip +import shutil +from botocore.exceptions import ClientError +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.application import MIMEApplication + +s3 = boto3.client("s3") + + +def lambda_handler(event, context): + mail_sender = "abc@abc.com" + mail_recipient = "efg@efg.com" + aws_region = "ap-east-1" + mail_subject = "Monthly billing csv 410429265162" + FILEOBJ = event["Records"][0] + BUCKET_NAME = str(FILEOBJ['s3']['bucket']['name']) + KEY = str(FILEOBJ['s3']['object']['key']) + FILE_NAME = os.path.basename(KEY) + temp_file = '/tmp/' + FILE_NAME + s3.download_file(BUCKET_NAME, KEY, temp_file) + with open(temp_file, 'rb') as f_in: + with gzip.open('billing-csv.gz', 'wb') as f_out: + shutil.copyfileobj(f_in, f_out) + ATTACHMENT = '/tmp/billing-csv.gz' + BODY_TEXT = "The Object file was uploaded to S3" + client = boto3.client('ses',region_name=aws_region) + msg = MIMEMultipart() + # Add subject, from and to lines. + msg['Subject'] = mail_subject + msg['From'] = mail_sender + msg['To'] = mail_recipient + textpart = MIMEText(BODY_TEXT) + msg.attach(textpart) + att = MIMEApplication(open(ATTACHMENT, 'rb').read()) + att.add_header('Content-Disposition','attachment',filename=ATTACHMENT) + msg.attach(att) + print(msg) + try: + response = client.send_raw_email( + Source=mail_sender, + Destinations=[mail_sender,mail_recipient], + RawMessage={ 'Data':msg.as_string() } + ) + except ClientError as e: + print(e.response['Error']['Message']) + else: + print("Email sent! Message ID:",response['MessageId']) diff --git a/py/aws-assume-role.py b/py/aws-assume-role.py index f68d872..0c6d677 100644 --- a/py/aws-assume-role.py +++ b/py/aws-assume-role.py @@ -1,8 +1,9 @@ +from typing import NoReturn import json import boto3 import base64 -def lambda_handler(event, context): +def lambda_handler(event, context) -> NoReturn: # TODO implement sts_client = boto3.client('sts') assumed_role_object=sts_client.assume_role( diff --git a/py/myrandom.py b/py/myrandom.py index 68c0200..cbe6139 100755 --- a/py/myrandom.py +++ b/py/myrandom.py @@ -1,14 +1,18 @@ #!/usr/bin/env python3 +from typing import NoReturn +#from passlib.hash import sha512_crypt +from passlib.hash import pbkdf2_sha512 import string -import crypt +#import crypt import threading from random import * characters = string.ascii_letters + "~@#%^*()-_+=23456789" -def genOne(): +def genOne() -> NoReturn: password = "".join(choice(characters) for x in range(randint(12, 16))); - salt = crypt.mksalt(method=crypt.METHOD_SHA512); - print (password, "|", crypt.crypt(password,salt=salt)); + #salt = crypt.mksalt(method=crypt.METHOD_SHA512); + #print (password, "|", crypt.crypt(password,salt=salt)); + print (password, "|", "$6$" + pbkdf2_sha512.hash(password).split('$')[-1]); for i in range(4): threading.Thread(target=genOne, args=()).start() diff --git a/py/port-test-with-cw-metric.py b/py/port-test-with-cw-metric.py new file mode 100644 index 0000000..625084c --- /dev/null +++ b/py/port-test-with-cw-metric.py @@ -0,0 +1,65 @@ +import json +import socket +import boto3 +import logging + +logger = logging.getLogger() +logger.setLevel(logging.INFO) + +def lambda_handler(event, context): + hosts=['10.129.72.63', '10.135.72.66', '10.129.72.64', '10.135.72.67'] + port=636 + timeout_seconds=3 + test_results = 0 + metric_value = 0 + for host in hosts: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(timeout_seconds) + result = sock.connect_ex((host,int(port))) + + if result == 0: + logger.info("Host {}:{} - Up".format(host, port)) + test_results += 1 + metric_value = 1 + else: + logger.error("Host {}:{} - Down".format(host, port)) + metric_value = 0 + sock.close() + + logger.info("Publishing cloudwatch metric...") + cloudwatch = boto3.client('cloudwatch') + try: + response = cloudwatch.put_metric_data( + MetricData=[ + { + 'MetricName': 'Ldap Tcp Test', + 'Dimensions': [ + { + 'Name': 'LdapHost', + 'Value': host + } + ], + 'Unit': 'None', + 'Value': metric_value + }, + ], + Namespace='Custom/Lambda' + ) + logger.info("Successfully published cloudwatch metric") + # logger.info(response) + except Exception as e: + logger.error("Error publishing cloudwatch metric: {}".format(str(e))) + + + if test_results == 4: + return { + 'message' : 'Successfully connected to all LDAP servers' + } + else: + raise Exception('Not all LDAP servers can be connected!') + + return { + 'statusCode': 200, + 'body': json.dumps("Finished") + } + diff --git a/py/print-env-ip.py b/py/print-env-ip.py new file mode 100755 index 0000000..277cab6 --- /dev/null +++ b/py/print-env-ip.py @@ -0,0 +1,6 @@ +#!/usr/bin/python3 +import socket +s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +s.connect(("8.8.8.8", 80)) +print(s.getsockname()[0]) +s.close()