【发布时间】:2015-09-26 04:16:16
【问题描述】:
在 boto3 上,如何扩展 ResourceModel?我不想做的是子类boto3.resources.factory.ec2.Instance 并为其添加run 方法。该方法将用于通过 SSH 在 Python 对象表示的 EC2 实例上远程运行命令。我希望以一种干净的方式来做到这一点,即不使用猴子补丁或其他晦涩的技术。
更新
基于Daniel's answer,我想出了以下代码。需要最新版本的 Boto 3,以及用于 SSH 连接的 Spur (pip install spur boto3)。
from boto3 import session
from shlex import split
from spur import SshShell
# Customize here.
REGION = 'AWS-REGION'
INSTID = 'AWS-INSTANCE-ID'
USERID = 'SSH-USER'
def hook_ssh(class_attributes, **kwargs):
def run(self, command):
'''Run a command on the EC2 instance via SSH.'''
# Create the SSH client.
if not hasattr(self, '_ssh_client'):
self._ssh_client = SshShell(self.public_ip_address, USERID)
print(self._ssh_client.run(split(command)).output.decode())
class_attributes['run'] = run
if __name__ == '__main__':
b3s = session.Session()
ec2 = b3s.resource('ec2', region_name=REGION)
# Hook the "run" method to the "ec2.Instance" resource class.
b3s.events.register('creating-resource-class.ec2.Instance', hook_ssh)
# Run some commands.
ec2.Instance(INSTID).run('uname -a')
ec2.Instance(INSTID).run('uptime')
【问题讨论】:
标签: python boto boto3 botocore