NEW: various python files

This commit is contained in:
xpk
2025-06-18 21:22:41 +08:00
parent 6c764730d3
commit 03797d6e8c
5 changed files with 135 additions and 9 deletions
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/pytho3
from pprint import pprint
import boto3
from datetime import datetime, timezone, timedelta
class Ami:
def __init__(self, name: str, age: int, delete: bool):
self.name = name
self.age = age
self.delete = delete
def __repr__(self):
return f"Ami(name='{self.name}', age={self.age}, delete={self.delete})"
def mark_for_deletion(self):
self.delete = True
ec2 = boto3.client("ec2")
images = ec2.describe_images(
Owners=["self"],
Filters=[
{"Name": "name", "Values": ["var*", "online-ordering-website*"]},
],
)
ami_in_use = []
launch_templates = ec2.describe_launch_templates()
for t in launch_templates.get("LaunchTemplates"):
latest = ec2.describe_launch_template_versions(
LaunchTemplateId=t.get("LaunchTemplateId"),
Versions=["$Latest"],
)
for lt in latest.get("LaunchTemplateVersions"):
ami_in_use.append(lt.get("LaunchTemplateData").get("ImageId"))
all_images = images.get("Images", [])
inactive_images = [i for i in all_images if i.get("ImageId") not in ami_in_use]
my_amis = {}
for i in all_images:
ami_id = i.get("ImageId")
ami_date = datetime.strptime(
i.get("CreationDate"), "%Y-%m-%dT%H:%M:%S.%fZ"
).replace(tzinfo=timezone.utc)
ami_age = datetime.now(timezone.utc) - ami_date
in_use = i.get("ImageId") not in ami_in_use
my_amis[i.get("ImageId")] = Ami(i.get("Name"), ami_age.days, in_use)
bno_images = {
k: v for k, v in my_amis.items() if v.name.startswith("var-backend-non-ordering")
}
bo_images = {
k: v for k, v in my_amis.items() if v.name.startswith("var-backend-ordering")
}
oo_images = {k: v for k, v in my_amis.items() if v.name.startswith("online-ordering")}
# sort and do not delete the newest 2
bno_sorted = sorted(bno_images.items(), key=lambda item: item[1].age)
for key, ami_obj in bno_sorted[:2]:
ami_obj.delete = False
bo_sorted = sorted(bo_images.items(), key=lambda item: item[1].age)
for key, ami_obj in bo_sorted[:2]:
ami_obj.delete = False
oo_sorted = sorted(oo_images.items(), key=lambda item: item[1].age)
for key, ami_obj in oo_sorted[:2]:
ami_obj.delete = False
pprint(bno_sorted)
pprint(bo_sorted)
pprint(oo_sorted)
+20
View File
@@ -0,0 +1,20 @@
"""
This program list all secrets and show their next rotation date if < 30d
"""
import boto3
from datetime import datetime, timezone
print("Secret DaysToNextRotation NextRotationDate")
sm_client = boto3.client('secretsmanager')
paginator = sm_client.get_paginator('list_secrets')
iterator = paginator.paginate()
for page in iterator:
for i in page.get('SecretList'):
if i.get("NextRotationDate") is not None:
NextRotationDate = i.get("NextRotationDate").replace(tzinfo=timezone.utc)
Today = datetime.now(timezone.utc)
Difference = (NextRotationDate - Today).days
# if Difference < 20:
print(i.get("Name"), Difference, NextRotationDate.date())
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/python3
"""
Documentation
Demonstrate how to use asyncio
License: This program is released under the MIT License
"""
# Imports
import asyncio
async def doit():
print('Start doing...')
await asyncio.sleep(2)
print('Done!')
# Main function
async def main() -> None:
print('Main starts...')
job_queue = []
for i in range(3):
job_queue.append(doit())
await asyncio.gather(*job_queue)
print('Main ends...')
# Call main function
if __name__ == '__main__':
asyncio.run(main())
+5 -5
View File
@@ -1,10 +1,10 @@
from terminaltables import SingleTable from terminaltables import SingleTable
table_data = [ table_data = [
['Heading1', 'Heading2'], ["Heading1", "Heading2"],
['row1 column1', 'row1 column2'], ["row1 column1", "row1 column2"],
['row2 column1', 'row2 column2'], ["row2 column1", "row2 column2"],
['row3 column1', 'row3 column2'] ["row3 column1", "row3 column2"],
] ]
t1 = SingleTable(table_data) t1 = SingleTable(table_data)
print (t1.table) print(t1.table)
+6 -4
View File
@@ -1,10 +1,12 @@
#!/usr/bin/python3 #!/usr/bin/python3
import urllib3 import urllib3
from urllib3 import Timeout from urllib3 import Timeout
from pprint import pprint
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
http = urllib3.PoolManager(cert_reqs='CERT_NONE') http = urllib3.PoolManager(cert_reqs="CERT_NONE")
url = "https://stats.oecd.org/" url = "https://blog.headdesk.me/"
r = http.request('GET', url, timeout=Timeout(10)) r = http.request("GET", url, timeout=Timeout(10))
print("statusCode: %s" % r.status) print(f"ResponseCode: {r.status}")
pprint(dict(r.headers))