Spaces:
Sleeping
Sleeping
File size: 5,421 Bytes
09afd55 |
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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
import boto3
import paramiko
import time
#ssh -i "my_kayname_01.pem" root@ec2-54-90-175-47.compute-1.amazonaws.com
# Replace these values with your actual values
access_key = "AKIAYIBNUHKTYGACURPX"
secret_key = "q8uXKrUQZx50zyIrPCUrnH/zvXNqv6QaR20O3Gaz"
region = "us-east-1"
image_id = "ami-088f3457fef51ee50"
instance_type = "r5.large" # Instance type with 32GB RAM
key_name = "my_kayname_01" # Replace with your key pair name
security_group_ids = ["sg-0452fd39f8266308d"]
def create_instance():
global access_key
global secret_key
global region
global image_id
global key_name
global security_group_ids
# Create a Boto3 EC2 client
ec2 = boto3.client("ec2", aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
# Launch an EC2 instance
response = ec2.run_instances(
ImageId=image_id,
InstanceType=instance_type,
KeyName=key_name,
MinCount=1,
MaxCount=1,
SecurityGroupIds=security_group_ids # Set the security group IDs here
)
instance = response["Instances"][0]
instance_id = response["Instances"][0]["InstanceId"]
print("Instance created:", instance_id)
response = ec2.describe_instances(InstanceIds=[instance_id])
# Extract the public IP address from the response
instance = response["Reservations"][0]["Instances"][0]
public_ip = instance.get("PublicIpAddress")
print(f"Instance created with IP: {public_ip}")
while True:
# Describe the status of the EC2 instance
response = ec2.describe_instance_status(InstanceIds=[instance_id])
# Extract system status and instance status details if available
if "InstanceStatuses" in response and len(response["InstanceStatuses"]) > 0:
instance_status = response["InstanceStatuses"][0]
system_status = response["InstanceStatuses"][0].get("SystemStatus", {})
instance_status_value = instance_status['InstanceStatus']['Status']
system_status_value = system_status.get('Status', 'N/A')
print(f"Instance Status: {instance_status_value}")
print(f"System Status: {system_status_value}")
if instance_status_value == "ok" and system_status_value == "ok":
break
time.sleep(10)
else:
print("Status checks not available for the instance.")
return instance_id, public_ip
def delete_instance(instance_id):
global access_key
global secret_key
global region
# Create a Boto3 EC2 client
ec2 = boto3.client("ec2", aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
# Terminate the EC2 instance
response = ec2.terminate_instances(InstanceIds=[instance_id])
# Print the response
print("Instance termination response:", response)
def ssh_connect(hostname):
#paramiko.util.log_to_file('paramiko.log')
#paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
# Replace these values with your actual ones
port = 22
username = "ec2-user"
#username = "ubuntu"
#username = "root"
key_filename = "my_kayname_01.pem" # Path to your private key file
# Create an SSH client instance
ssh_client = paramiko.SSHClient()
# Automatically add the server's host key (this is insecure and not recommended for production)
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Connect to the EC2 instance
ssh_client.connect(hostname, port, username, key_filename=key_filename)
# Execute a command on the remote instance (e.g., list directory contents)
stdin, stdout, stderr = ssh_client.exec_command("ls -l")
# Print the output of the command
print(stdout.read().decode("utf-8"))
# Install Jupyter Notebook using pip
install_command = "pip install jupyter"
stdin, stdout, stderr = ssh_client.exec_command(install_command)
print(stdout.read().decode("utf-8"))
# Start the Jupyter Notebook server (you can specify your desired options)
jupyter_command = "jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser"
ssh_client.exec_command(jupyter_command)
print("Jupyter Notebook installed and server started.")
# Start the Jupyter Notebook server (you can specify your desired options)
jupyter_command = "jupyter server list"
while True:
stdin, stdout, stderr = ssh_client.exec_command(jupyter_command)
stdout_value = stdout.read().decode("utf-8")
if stdout_value.find("http:") != -1:
break
time.sleep(3)
print(stdout_value)
p = stdout_value.find("http:")
if p != -1:
temp = stdout_value[p:]
p = temp.find("?token")
if p != -1:
temp = temp[p + 7:]
p = temp.find(" :: ")
token_value = temp[: p]
print("token=", token_value)
# Close the SSH connection
ssh_client.close()
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
instance_id, public_ip = create_instance()
ssh_connect(public_ip)
#ssh_connect("44.210.108.226")
#delete_instance(instance_id)
|