boto3 पर, मैं ResourceModel
कैसे बढ़ा सकता हूं? मुझे जो करना है वह सबक्लास boto3.resources.factory.ec2.Instance
है और इसमें run
विधि जोड़ें। एसएसएच के माध्यम से पाइथन ऑब्जेक्ट द्वारा प्रतिनिधित्व किए गए ईसी 2 इंस्टेंस पर आदेशों को दूरस्थ रूप से चलाने के लिए उस विधि का उपयोग किया जाएगा। मैं इसे एक साफ तरीके से करना चाहता हूं, यानी बंदर पैच या अन्य अस्पष्ट तकनीकों का उपयोग किए बिना।Boto3 संसाधन का विस्तार कैसे करें?
अद्यतन
पर Daniel's answer आधार पर, मैं निम्नलिखित कोड के साथ आया था। एसएसएच कनेक्शन (pip install spur boto3
) के लिए बोटो 3 के हालिया संस्करण और Spur की आवश्यकता है।
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')
धन्यवाद डैनियल। मैंने आपके द्वारा दिए गए संसाधनों पर आधारित कुछ कोड लिखा है। जब मैं boto3 तैयार हो जाता हूं तो मैं इसे चलाने की कोशिश करूंगा। – Rafa
यह विषय अब [एक्सटेंसिबिलिटी गाइड] (http://boto3.readthedocs.org/en/latest/guide/events.html) के तहत boto3 दस्तावेज़ों में शामिल है। –
धन्यवाद बेन। मैंने एक रननेबल कोड स्निपेट के साथ प्रश्न अपडेट किया है और यह जवाब स्वीकार कर लेगा। – Rafa