How to SSH and run commands in EC2 using boto3?

前端 未结 6 1988
情深已故
情深已故 2020-12-03 05:02

I want to be able to ssh into an EC2 instance, and run some shell commands in it, like this.

How do I do it in boto3?

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 05:28

    Here is how I have done

    import boto3
    import botocore
    import boto
    import paramiko
    
    ec2 = boto3.resource('ec2')
    
    instances = ec2.instances.filter(
        Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
    i = 0
    for instance in instances:
        print(instance.id, instance.instance_type)
        i+= 1
    x = int(input("Enter your choice: "))
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        privkey = paramiko.RSAKey.from_private_key_file('address to .pem key')
        ssh.connect(instance.public_dns_name,username='ec2-user',pkey=privkey)
        stdin, stdout, stderr = ssh.exec_command('python input_x.py')
        stdin.flush()
        data = stdout.read().splitlines()
        for line in data:
            x = line.decode()
            #print(line.decode())
            print(x,i)
            ssh.close()
    

    For the credentails, I have added AWSCLI package, then in the terminal run

    aws configure
    

    enter the credentials. All of them will be saved in .aws folder, u can change the path too.

提交回复
热议问题