os, subprocess/ssh
code: python
import subprocess
import os
from dotenv import load_dotenv
from typing import Optional, Dict
load_dotenv()
def ssh_command(pem_path: str, host: str, command: str) -> Optionalstr: try:
cmd = [
'ssh',
'-i', pem_path,
'-o', 'StrictHostKeyChecking=accept-new',
f'ec2-user@{host}',
command
]
result = subprocess.run(
cmd,
capture_output=True,
text=True,
)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"Error executing command: {e.stderr}")
return None
except Exception as e:
print(f"An error occurred: {e}")
return None
def get_system_info(pem_path: str, host: str) -> Dictstr, str: info = {
'kernel_version': None,
'architecture': None
}
kernel = ssh_command(pem_path, host, 'uname -r')
if kernel:
arch = ssh_command(pem_path, host, 'uname -m')
if arch:
return info
def main():
pem_path = os.getenv("PEM_PATH")
host = os.getenv("EC2_HOST")
try:
os.chmod(pem_path, 0o400)
system_info = get_system_info(pem_path, host)
else:
print("Failed to get kernel version")
else:
print("Failed to get architecture")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()