How to SSH and run commands in EC2 using boto3?

前端 未结 6 1972
情深已故
情深已故 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:29

    You can use the following code snippet to ssh to an EC2 instance and run some command from boto3.

    import boto3
    import botocore
    import paramiko
    
    key = paramiko.RSAKey.from_private_key_file(path/to/mykey.pem)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    # Connect/ssh to an instance
    try:
        # Here 'ubuntu' is user name and 'instance_ip' is public IP of EC2
        client.connect(hostname=instance_ip, username="ubuntu", pkey=key)
    
        # Execute a command(cmd) after connecting/ssh to an instance
        stdin, stdout, stderr = client.exec_command(cmd)
        print stdout.read()
    
        # close the client connection once the job is done
        client.close()
        break
    
    except Exception, e:
        print e
    

提交回复
热议问题