用于自动创建事物,策略,证书的Python程序,用于aws iot控制台界面中所需的所有东西

时间:2018-03-23 13:29:45

标签: python aws-lambda boto3

我使用aws-iot-sdk-node.js进行程序化生成。 [https://aws.amazon.com/blogs/compute/implementing-a-serverless-aws-iot-backend-with-aws-lambda-and-amazon-dynamodb/][1] 但我希望python程序通过生成事物,策略,证书和下载证书来自动注册raspberry pi以供进一步使用。

var AWS = require('aws-sdk');
AWS.config.region = 'region';
AWS.config.update({
    accessKeyId: "your Key",
    secretAccessKey: "your Key",
});

var iot = new AWS.Iot();
var crypto = require('crypto');
var endpoint = "your endpoint"
var iotdata = new AWS.IotData({endpoint: endpoint});
var topic = "registration";
var type = "MySmartIoTDevice"

//Create 50 AWS IoT Things
for(var i = 1; i < 51; i++) {
  var serialNumber = "SN-"+crypto.randomBytes(Math.ceil(12/2)).toString('hex').slice(0,15).toUpperCase();
  var clientId = "ID-"+crypto.randomBytes(Math.ceil(12/2)).toString('hex').slice(0,12).toUpperCase();
  var activationCode = "AC-"+crypto.randomBytes(Math.ceil(20/2)).toString('hex').slice(0,20).toUpperCase();
  var thing = "myThing"+i.toString();
  var thingParams = {
    thingName: thing
  };

  iot.createThing(thingParams).on('success', function(response) {
    //Thing Created!
  }).on('error', function(response) {
    console.log(response);
  }).send();

  //Publish JSON to Registration Topic

  var registrationData = '{\n \"serialNumber\": \"'+serialNumber+'\",\n \"clientId\": \"'+clientId+'\",\n \"device\": \"'+thing+'\",\n \"endpoint\": \"'+endpoint+'\",\n\"type\": \"'+type+'\",\n \"activationCode\": \"'+activationCode+'\",\n \"activated\": \"false\",\n \"email\": \"not@registered.yet\" \n}';

  var registrationParams = {
    topic: topic,
    payload: registrationData,
    qos: 0
  };

  iotdata.publish(registrationParams, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    // else Published Successfully!
  });
  setTimeout(function(){},50);
}

//Checking all devices were created

iot.listThings().on('success', function(response) {
  var things = response.data.things;
  var myThings = [];
  for(var i = 0; i < things.length; i++) {
    if (things[i].thingName.includes("myThing")){
      myThings[i]=things[i].thingName;
    }
  }

  if (myThings.length = 50){
    console.log("myThing1 to 50 created and registered!");
  }
}).on('error', function(response) {
  console.log(response);
}).send();

这是我的示例javascript代码来扩展我的IOT项目。我想使用python自动创建事物,策略,证书和下载证书来执行相同的任务。之后我想将传感器数据存储到Dynamo db中事情影。请告诉我完成这项任务的正确方法。

2 个答案:

答案 0 :(得分:0)

是的,你的java脚本代码正常工作,我也在搜索你问过的同一个问题。我找到了一些有用的参考文献here

答案 1 :(得分:0)

以下是来自here的python程序的完整参考:

创造物品

iot.create_thing(thingName="t_name")

用于创建证书并将其存储在存储库中

 with open(certname, "w") as pem_file:
            # out_file.write(things[i][thing_name])
            pem = things[i][t_name]['certificatePem']
            pem_file.write(pem)
            log.info("Thing Name: {0} and PEM file: {1}".format(
                t_name, certname))

        with open(public_key_file, "w") as pub_file:
            pub = things[i][t_name]['keyPair']['PublicKey']
            pub_file.write(pub)
            log.info("Thing Name: {0} Public Key File: {1}".format(
                t_name, public_key_file))

        with open(private_key_file, "w") as prv_file:
            prv = things[i][t_name]['keyPair']['PrivateKey']
            prv_file.write(prv)
            log.info("Thing Name: {0} Private Key File: {1}".format(
                t_name, private_key_file))

用于创建和附加政策

tp = {
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": [
            # "iot:*"
            "iot:Connect",
            "iot:Publish",
            "iot:Receive",
            "iot:Subscribe"
        ],
        "Resource": [
            "arn:aws:iot:{0}:*:*".format(region)
        ]
    }]
}

iot = _get_iot_session(region, cli.profile_name)
policy_name = 'policy-{0}'.format(thing_name)
policy = json.dumps(tp)
log.debug('[_create_and_attach_policy] policy:{0}'.format(policy))
p = iot.create_policy(
    policyName=policy_name,
    policyDocument=policy
)