如何使用boto3在EC2中SSH和运行命令? [英] How to SSH and run commands in EC2 using boto3?
本文介绍了如何使用boto3在EC2中SSH和运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够通过SSH进入EC2实例,并在其中运行一些shell命令,例如此。
I want to be able to ssh into an EC2 instance, and run some shell commands in it, like this.
我如何在boto3中做到这一点?
How do I do it in boto3?
推荐答案
您可以使用以下代码段SSH到EC2实例并从boto3运行一些命令。
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
这篇关于如何使用boto3在EC2中SSH和运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文