宝途的EC2实例执行shell命令实例、命令、shell

2023-09-11 23:38:17 作者:余生若安

我是新手,以EC2和博托。我有运行实例的EC2,我想执行例如像一个shell命令易于得到通过博托更新

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.

我搜索了很多,发现使用 USER_DATA 的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,
                                     key_path='<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.

您也可以检查出布( 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.