【问题标题】:AWS SQS: Sending dynamic message using botoAWS SQS:使用 boto 发送动态消息
【发布时间】:2016-08-14 04:33:02
【问题描述】:

我有一个工作 python/boto 脚本,它向我的 AWS SQS 队列发布一条消息。然而,消息正文被硬编码到脚本中。

我创建了一个名为 ~/file 的文件,其中包含两个值

$ cat ~/file
Username 'encrypted_password_string'

我希望我的 boto 脚本(见下文)向我的 AWS SQS 队列发送一条包含这两个值的消息。

谁能告诉我如何在下面修改我的脚本,以便发送到 SQS 的消息正文包含文件 ~/file.txt 的内容。另请注意加密密码字符串中存在的特殊字符

示例: ~/文件 用户名 d5MopV/EsfSKk8BExCyLHFwNfBrOTzQ1

#!/usr/bin/env python

conf = {
  "sqs-access-key": "xxxx",
  "sqs-secret-key": "xxxx",
  "sqs-queue-name": "UserPassChange",
  "sqs-region": "xxxx",
  "sqs-path": "sqssend"
}

import boto.sqs
conn = boto.sqs.connect_to_region(
        conf.get('sqs-region'),
        aws_access_key_id       = conf.get('sqs-access-key'),
        aws_secret_access_key   = conf.get('sqs-secret-key')
)

q = conn.create_queue(conf.get('sqs-queue-name'))

from boto.sqs.message import RawMessage
m = RawMessage()
m.set_body('hardcoded message')
retval = q.write(m)
print 'added message, got retval: %s' % retval

一种让它工作的方法:

在我添加的脚本中

import commands

然后添加,

USERNAME = commands.getoutput("echo $(who am i | awk '{print $1}')")    
PASS = commands.getoutput("cat /tmp/.s")

然后将这些值添加到我的消息正文中:

MSG = RawMessage()    
MSG.set_body(json.dumps({'pass': PASS, 'user': USERNAME}))

【问题讨论】:

  • 首先,停止使用boto,开始使用boto3。一旦进入 boto3,您只需要按照这里的示例进行操作:boto3.readthedocs.io/en/latest/guide/sqs.html 请记住,boto3 有一个高资源方法 boto3.resource() 并且还允许您使用低级别 boto3.client() 方法。如果您打算编写包装器,请记住将它们记录下来。
  • 感谢 mootmoot 但这并不能回答我如何在上面提到的脚本中输入动态值的问题。
  • 老实说,你应该澄清你的问题和你的意图。奇怪的是,您使用 who am i 来获取用户名但在您的问题中未提及。然后突然跳转到/tmp/.s。请澄清它或冒着被改装的风险。
  • 你提到的Please also take note of the special characters that exists within a encrypted password string 太模棱两可了。 special character 是什么意思?是二进制还是unicode?还是base64编码?

标签: python-2.7 amazon-web-services boto amazon-sqs


【解决方案1】:

以下示例展示了如何使用 Boto3 将文件发送到接收者。

test_sqs.py

import boto3
from moto import mock_sqs

@mock_sqs
def test_sqs():
    sqs = boto3.resource('sqs', 'us-east-1')
    queue = sqs.create_queue(QueueName='votes')

    queue.send_message(MessageBody=open('beer.txt').read())

    messages = queue.receive_messages()
    assert len(messages) == 1
    assert messages[0].body == 'tasty\n'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多