NEW: various new scripts

This commit is contained in:
xpk 2024-02-22 15:37:33 +08:00
parent fff64beb1c
commit 6a427f2ef8
Signed by: xpk
GPG Key ID: CD4FF6793F09AB86
9 changed files with 166 additions and 5 deletions

9
aws/aws-config-status.sh Executable file
View File

@ -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

3
aws/aws-endpoint-inventory.sh Executable file
View File

@ -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

8
aws/gzip-file.py Executable file
View File

@ -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)

15
aws/iam-user-audit.sh Executable file
View File

@ -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

50
aws/s3-file-email.py Normal file
View File

@ -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'])

View File

@ -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(

View File

@ -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()

View File

@ -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")
}

6
py/print-env-ip.py Executable file
View File

@ -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()