请问我是否可以在AWS实例上使用boto3
执行shell命令?
我在一些地方读到了boto.manage.cmdshell
,但它在boto3
中已被弃用。
请问我是否可以在AWS实例上使用boto3
执行shell命令?
我在一些地方读到了boto.manage.cmdshell
,但它在boto3
中已被弃用。
ssm_client = boto3.client('ssm')
response = ssm_client.send_command(
InstanceIds=['i-03#####'],
DocumentName="AWS-RunShellScript",
Parameters={'commands': ['start ecs']}, )
command_id = response['Command']['CommandId']
output = ssm_client.get_command_invocation(
CommandId=command_id,
InstanceId='i-03######',
)
print(output)
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。我将它放在OutputS3KeyPrefix中,以获取存储桶中唯一的日志存储位置。
您可以按照以下步骤安装SSM Agent:
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
)
我知道我在回答一个有点老的帖子。我甚至不确定在那个时候SSM是否存在。但现在你可以使用boto3中的SSM send_command直接在EC2实例上运行命令。
这里是在EC2实例上运行PowerShell命令的示例:
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)
更多信息,请阅读Boto3 SSM文档。有关SSM本身的信息,请参考AWS文档。
boto.manage.cmdshell
的功能没有迁移到boto3。原始的boto.manage.cmdshell
功能使用了Paramiko,如果您想在boto3中使用SSH功能,可以直接使用Paramiko。修改
command_id = response['Command']['CommandId']
到
command_id = context.aws_request_id
文档中提到:
aws_request_id
与请求相关联的AWS请求ID。这是返回给调用调用方法的客户端的ID。
更改为:
command_id = response['Command']['CommandId']
for:
command_id = context.aws_request_id