2015-12-01 59 views

回答

2

号中博托的boto.manage.cmdshell功能并未被迁移到boto3。原来的boto.manage.cmdshell功能使用Paramiko,你可以直接与boto3一起使用,如果你想使用boto3的SSH功能。

这是关于此主题的boto3 github issue

由于@jarmod指出截至2015年10月有new AWS functionality,使您可以使用AWS EC2 SSM在Windows系统上运行命令。您可以在博客3中使用boto3 SSM client从botocore版本1.3.1开始访问。

扶持 “EC2上运行命令”

+0

非常感谢这个样品。我要去尝试帕拉米科。 – sdeshpande

+2

另请参阅最近发布的EC2运行命令:https://aws.amazon.com/blogs/aws/new-ec2-run-command-remote-instance-management-at-scale/。这个博客表明它支持boto3和awscli,尽管我还没有找到它。以下是常见问题解答:https://aws.amazon.com/ec2/run-command/faqs/ – jarmod

+0

不适用于我 – Gil

1
ssm = boto3.client('ssm')  
testCommand = ssm.send_command(InstanceIds=[ 'i-123123123123' ], DocumentName='AWS-RunShellScript', Comment='la la la', OutputS3BucketName='myOutputS3Bucket', OutputS3KeyPrefix='i-123123123123', Parameters={ "commands":[ "ip config" ] }) 

I-123123123123只是假装EC2实例ID这里有一个boto3 github issue。 我把它放在OutputS3KeyPrefix中以获得一个独特的地方来存储桶中的日志。

您可以像这样安装ssm代理;

ec2r = boto3.resource('ec2') 
userdata = """#cloud-config 
    runcmd: 
    - /home/ec2-user/sudo npm run prod 
    - cd /tmp 
    - curl https://amazon-ssm-%s.s3.amazonaws.com/latest/linux_amd64/amazon-ssm-agent.rpm -o amazon-ssm-agent.rpm 
    - yum install -y amazon-ssm-agent.rpm 
""" % region 

if ssm == "on": 
    instance = ec2r.create_instances(ImageId=ami, MinCount=1, MaxCount=1, KeyName=keyname, InstanceType=instancetype, 
     NetworkInterfaces=[{ 
     'DeviceIndex': 0, 
     'AssociatePublicIpAddress': False, 
     'SubnetId': mySub, 
     'Groups': secGroupList, 
     'AssociatePublicIpAddress': AssociatePublicIpAddress 
    }], 
     Monitoring={ 'Enabled': False }, 

     UserData=userdata, 
     IamInstanceProfile={ 
      'Name': rolename 
     }, 
     EbsOptimized=False 
    ) 
+0

感谢您发布此解决方案。作为有经验的人,你会主张使用paramiko而不是简单的SSM吗?这里的github问题的开发人员: https://github.com/boto/boto3/issues/328 似乎更喜欢它通过SSM执行shell脚本。 –

+0

我已经进入了部署云构建的模板。它有助于清楚您已经在cf控制台中部署了什么。 – ddtraveller

0

我知道我回答的是旧线程。我不确定当时是否存在SSM。但是现在可以使用来自boto3的SSM send_command在ec2实例上直接运行命令。 这里是运行在EC2实例

import boto3 
ssm_client = boto3.client('ssm', region_name="us-west-2") # use region code in which you are working 
response = ssm_client.send_command(
      InstanceIds=[ 
       "i-03########" # use instance id on which you want to execute, even multiple is allowd 
        ], 
      DocumentName="AWS-RunPowerShellScript", 
      Parameters={ 
       'commands':[ 
        'ipconfig' 
         ] 
        }, 
      }) 
command_id = response['Command']['CommandId'] 
output = ssm_client.get_command_invocation(
     CommandId=command_id, 
     InstanceId='i-03######', 
    ) 
print(output) 

PowerShell命令欲了解更多信息,请阅读boto3 SSM docs 有关SSM信息本身参阅AWS文档