Boto 在 ec2 实例上执行 shell 命令 [英] Boto Execute shell command on ec2 instance

查看:17
本文介绍了Boto 在 ec2 实例上执行 shell 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 EC2 和 boto 的新手.我有一个 EC2 运行实例,我想执行一个 shell 命令,例如apt-get update 通过 boto.

I am newbie to EC2 and boto. I have an EC2 running instance and I want to execute a shell command like e.g. apt-get update through boto.

我搜索了很多,并在 run_instances 命令,但如果实例已经启动怎么办?

I searched a lot and found a solution using user_data in the run_instances command, but what if the instance is already launched?

我什至不知道这是否可能.此参考资料中的任何线索都会有很大帮助.

I don't even know if it is possible. Any clue in this reference will be a great help.

推荐答案

boto.manage.cmdshell 模块可用于执行此操作.要使用它,您必须安装 paramiko 包.一个简单的例子:

The boto.manage.cmdshell module can be used to do this. To use it, you must have the paramiko package installed. A simple example of it's use:

import boto.ec2
from boto.manage.cmdshell import sshclient_from_instance

# Connect to your region of choice
conn = boto.ec2.connect_to_region('us-west-2')

# Find the instance object related to my instanceId
instance = conn.get_all_instances(['i-12345678'])[0].instances[0]

# Create an SSH client for our instance
#    key_path is the path to the SSH private key associated with instance
#    user_name is the user to login as on the instance (e.g. ubuntu, ec2-user, etc.)
ssh_client = sshclient_from_instance(instance,
                                     '<path to SSH keyfile>',
                                     user_name='ec2-user')
# Run the command. Returns a tuple consisting of:
#    The integer status of the command
#    A string containing the output of the command
#    A string containing the stderr output of the command
status, stdout, stderr = ssh_client.run('ls -al')

那是凭记忆打出来的,但我认为它是正确的.

That was typed from memory but I think it's correct.

您还可以查看具有类似功能的 Fabric(http://docs.fabfile.org/)功能,但还具有更复杂的特性和功能.

You could also check out Fabric (http://docs.fabfile.org/) which has similar functionality but also has much more sophisticated features and capabilities.

这篇关于Boto 在 ec2 实例上执行 shell 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆