Exemplo n.º 1
1
def send_temperature(temp):
    today = datetime.datetime.now()
    now = str(today)    
    sbs = ServiceBusService(service_namespace=sb_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value)    
    print ('sending to Event Hub...@' + now)
    event_message = '{ "DeviceId": "' + device_id + '", "DeviceName": "' + device_name + '", "Temperature": "' + str(temp) + '", "TimeStamp": "' + now + '" }'
    print (event_message)
    sbs.send_event(hub_name, event_message)            
    print ('sent!')    
Exemplo n.º 2
0
def main():
  parser = argparse.ArgumentParser(description='Run automated diagnostics')
  parser.add_argument('-y', action='store_true', help='Skip prompts')
  parser.add_argument('--anonymous', action='store_true', help='No telemetry')
  parser.add_argument('--case', help='Link output with a case, for use with Azure Support')
  parser.add_argument('--human', action='store_true', help='Write human-readable text to stdout')
  parser.add_argument('--feedback', action='store_true', help='Provide suggestions and/or feedback')

  args=parser.parse_args()

  if(args.feedback):
    suggestion = raw_input("Suggestion (Press return to submit):  ")
    sbkey = '5QcCwDvDXEcrvJrQs/upAi+amTRMXSlGNtIztknUnAA='
    sbs = ServiceBusService('linuxdiagnostics-ns', shared_access_key_name='PublicProducer', shared_access_key_value=sbkey)
    event = {'event': 'feedback', 'feedback': suggestion}
    sbs.send_event('linuxdiagnostics',json.dumps(event))
    exit()

  if(args.anonymous):
    if(args.case == True):
      print "Cannot report case diagnostics in anonymous mode."
    else:
      Diagnostics(False,args.case).print_report(args.human)
  else:
    if(args.y):
      Diagnostics(True,args.case).print_report(args.human)
    else:
      prompt="In order to streamline support and drive continuous improvement, this script may transmit system data to Microsoft.\n Do you consent to this? (y/n):"
      consent=raw_input(prompt)
      if(consent=='y' or consent=='Y'):
        Diagnostics(True,args.case).print_report(args.human)
      else:
        print("To run without telemetry, use the --anonymous flag")
Exemplo n.º 3
0
def main():
    sbs = ServiceBusService(
        service_namespace='holEvents',
        shared_access_key_name='RootManageSharedAccessKey',
        shared_access_key_value='ugV/8wxg/Z0ZoTWBZWRUP5j2cgaEDiJC26ZLuoshotY=')
    turn = 0
    while turn >= 0:
        t = rd(19.6, 67.6)
        ap = rd(1002.6, 101.1)
        rh = rd(54, 13.6)
        v = rd(83.5, 99.1)
        pe = rd(445.6, 61.1)

        now = datetime.now().strftime("%M")

        if turn == 0:
            time = now
        else:
            if now != time:

                data = {
                    "T": str(t),
                    "V": str(v),
                    "AP": str(ap),
                    "RH": str(rh),
                    "PE": str(pe)
                }

                body = str.encode(json.dumps(data))
                print(body)
                sbs.send_event('datatostream', body)

                time = now

        turn += 1
Exemplo n.º 4
0
class Diagnostics:
  def __init__(self,telemetry,case):
    self.sbkey = '5QcCwDvDXEcrvJrQs/upAi+amTRMXSlGNtIztknUnAA='
    self.sbs = ServiceBusService('linuxdiagnostics-ns', shared_access_key_name='PublicProducer', shared_access_key_value=self.sbkey)
    self.telemetry = telemetry
    self.case = case
    self.report = dict()
    self.data = dict()
    try:
      self.data['fstab'] = fstab()
      self.data['vmstat'] = vmstat()
      self.data['diskstats'] = diskstats()
      self.data['meminfo'] = meminfo()
      self.data['loadavg'] = loadavg()
      self.data['proc.sys.fs'] = procsysfs()
      self.data['inodes_by_mount'] = inodes_by_mp()
      self.data['waagent'] = waagent()
      self.check_fstab_uuid()
      self.check_resourcedisk_inodes()
      self.success_telemetry()
    except:
      self.error_telemetry(str(sys.last_value))
      exit()

  def print_report(self,human):
    if(human):
      for item in map(lambda x: human_readable(self.report[x]),self.report):
        print item
    else:
      print json.dumps(self.report)

# == Telemetry ==
  def success_telemetry(self):
    if(self.telemetry):
      event = {'event': 'success', 'report': self.report, 'data': self.data}
      if(self.case):
        event['case'] = self.case
      self.sbs.send_event('linuxdiagnostics',json.dumps(event))

  def error_telemetry(self,e):
    if(self.telemetry):
      event = {'event': 'error', 'error': e, 'report': self.report, 'data':self.data}
      if(self.case):
        event['case'] = self.case
      sbs.send_event('linuxdiagnostics',json.dumps(event))

# == Diagnostics ==
  def check_fstab_uuid(self):
    uuids = map (lambda r:bool(re.match('UUID',r['fs_spec'],re.I)), self.data['fstab'])
    uuids = filter(lambda x: not x, uuids)
    if(len(uuids) > 0):
      self.report['linux.uuid']= report("fstab doesn't use UUIDs", 'red', 'best_practices', "/etc/fstab isn't using UUIDs to reference its volumes.", '')

  def check_resourcedisk_inodes(self):
    mountpoint = self.data['waagent']['ResourceDisk.MountPoint']
    x=filter(lambda x: x['mountpoint']==mountpoint ,self.data['inodes_by_mount'])[0]
    if(x['inodes_used'] > 20):
      self.report['azure.resource_disk_usage'] = report('Resource Disk Usage', 'yellow', 'data_loss',"This instance appears to be using the resource disk. Data stored on this mountpoint may be lost.", '')
Exemplo n.º 5
0
class EventHubSender(BaseSender):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._sender = ServiceBusService(self._config.service_namespace,
                                         shared_access_key_name=self._config.key_name,
                                         shared_access_key_value=self._config.key_value)

    def send(self, label, data):
        assert isinstance(label, str), 'label must be a string'
        self._sender.send_event(label, data)
Exemplo n.º 6
0
def send_msg_bus(namespace, hub, user, password):
    from azure.servicebus import ServiceBusService, Message, Queue
    from datetime import datetime
    import subprocess
    bus_service = ServiceBusService(service_namespace=namespace,
                                    shared_access_key_name=user,
                                    shared_access_key_value=password)
    message = subprocess.getoutput('az resource list -o json')
    #  message = 'mon script,"{}"'
    bus_service.send_event(hub, message)
Exemplo n.º 7
0
def send_temperature(temp):
    today = datetime.datetime.now()
    now = str(today)
    sbs = ServiceBusService(service_namespace=sb_namespace,
                            shared_access_key_name=key_name,
                            shared_access_key_value=key_value)
    print('sending to Event Hub...@' + now)
    event_message = '{ "DeviceId": "' + device_id + '", "DeviceName": "' + device_name + '", "Temperature": "' + str(
        temp) + '", "TimeStamp": "' + now + '" }'
    print(event_message)
    sbs.send_event(hub_name, event_message)
    print('sent!')
    def on_data(self, data):

        # Twitter returns data in JSON format - we need to decode it first
		decoded = json.loads(data)

        # # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
        # print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
        # print ''
        # return True

		sbs = ServiceBusService(service_namespace=config.servns, shared_access_key_name=config.key_name, shared_access_key_value=config.key_value)
		searched_tweets = "{ 'source': '" + unicode(decoded['user']['screen_name']) + "' , 'text': '" + unicode(decoded['text'].encode('ascii', 'ignore')) + "' }"
		print(unicode(searched_tweets))
		sbs.send_event('iot', unicode(searched_tweets))

		return True
Exemplo n.º 9
0
def main():
    appkey = "24000e5c1b5338a94f68ce841d975f8a"  # juhe-api

    # Azure service
    sbs = ServiceBusService(
        service_namespace='brucewaynetolltooth',
        shared_access_key_name='RootManageSharedAccessKey',
        shared_access_key_value='m6mWS29LUMIh2ZH9gh4KjmoNPiXBxeMCaq6eMxojBDc=')

    while True:
        print("Query starts...")
        page_quantity_query = 10  # 请求页数
        for page in range(1, page_quantity_query):
            api_result = request4(appkey, "GET", page)  # 香港股市列表
            s = json.dumps(api_result)
            sbs.send_event('entrysignals', s)
        time.sleep(60)  # 1000次每日限额,每1分钟请求10次,100分钟用完
Exemplo n.º 10
0
class listener(StreamListener):
    whitespace_regex = re.compile('\s+')
    connection_string_regex = re.compile(
        '^Endpoint=sb://(.+).servicebus.windows.net/;SharedAccessKeyName=(.+);SharedAccessKey=(.+);EntityPath=(.+)$'
    )

    def __init__(self, event_hub_connection_string, keywords):
        m = self.connection_string_regex.match(event_hub_connection_string)
        self.sbs = ServiceBusService(m.group(1),
                                     shared_access_key_name=m.group(2),
                                     shared_access_key_value=m.group(3))
        self.keywords = keywords
        self.event_hub_name = m.group(4)

    def on_data(self, data):
        try:
            tweet = json.loads(data)
            p = re.compile('\s+')
            text = tweet['text']
            for topic in self.get_topics(text, keywords):
                output = json.dumps({
                    'text': text,
                    'timestamp_ms': tweet['timestamp_ms'],
                    'topic': topic,
                    'id': tweet['id'],
                    'retweet_count': tweet['retweet_count'],
                    'time_zone': tweet['user']['time_zone'],
                    'lang': tweet['user']['lang']
                })
                self.sbs.send_event(self.event_hub_name, output)
            return True
        except BaseException as e:
            print('failed ondata' + str(e))
            time.sleep(5)

    def on_error(self, status):
        print(status)

    def get_topics(self, input, keywords):
        return [
            keyword for keyword in self.keywords
            if self.sanitize_text(keyword) in self.sanitize_text(input)
        ]

    def sanitize_text(self, input):
        return self.whitespace_regex.sub(' ', input.strip().lower())
Exemplo n.º 11
0
    def on_success(self, data):
        sbs = ServiceBusService(
            config.a_event_hub_namespace,
            shared_access_key_name=config.a_shared_access_key_name,
            shared_access_key_value=config.a_shared_access_key_value)
        D = {}

        if 'text' in data:
            D["timestamp"] = data['timestamp_ms']
            D["tweet_id"] = data['id_str']
            D["user_id"] = data['user']['id_str']
            D["screen_name"] = data['user']['screen_name']

            if data['truncated'] is True:
                D["tweet"] = re.sub("'", "|",
                                    data['extended_tweet']['full_text'])
            else:
                D["tweet"] = re.sub("'", "|", data['text'])

            D["retweeted_id"] = ''
            D["retweeted_user_id"] = ''
            D["retweet"] = 0

            if 'retweeted_status' in data:
                D["retweeted_id"] = data['retweeted_status']['id_str']
                D["retweeted_user_id"] = data['retweeted_status']['user'][
                    'id_str']
                D["retweet"] = 1

            list = ''
            for lists in data['entities']['hashtags']:
                list = list + lists['text'] + ' '

            D["hashtags"] = list

            print(data['timestamp_ms'])
            sbs.send_event("twitterstreamin",
                           json.dumps(D, ensure_ascii=False).encode('utf8'))

        else:
            for key, value in data.items():
                print(key, ' : ', value)

        return True
Exemplo n.º 12
0
def main():
    parser = argparse.ArgumentParser(description='Run automated diagnostics')
    parser.add_argument('-y', action='store_true', help='Skip prompts')
    parser.add_argument('--anonymous',
                        action='store_true',
                        help='No telemetry')
    parser.add_argument(
        '--case', help='Link output with a case, for use with Azure Support')
    parser.add_argument('--human',
                        action='store_true',
                        help='Write human-readable text to stdout')
    parser.add_argument('--feedback',
                        action='store_true',
                        help='Provide suggestions and/or feedback')

    args = parser.parse_args()

    if (args.feedback):
        suggestion = raw_input("Suggestion (Press return to submit):  ")
        sbkey = '5QcCwDvDXEcrvJrQs/upAi+amTRMXSlGNtIztknUnAA='
        sbs = ServiceBusService('linuxdiagnostics-ns',
                                shared_access_key_name='PublicProducer',
                                shared_access_key_value=sbkey)
        event = {'event': 'feedback', 'feedback': suggestion}
        sbs.send_event('linuxdiagnostics', json.dumps(event))
        exit()

    if (args.anonymous):
        if (args.case == True):
            print "Cannot report case diagnostics in anonymous mode."
        else:
            Diagnostics(False, args.case).print_report(args.human)
    else:
        if (args.y):
            Diagnostics(True, args.case).print_report(args.human)
        else:
            prompt = "In order to streamline support and drive continuous improvement, this script may transmit system data to Microsoft.\n Do you consent to this? (y/n):"
            consent = raw_input(prompt)
            if (consent == 'y' or consent == 'Y'):
                Diagnostics(True, args.case).print_report(args.human)
            else:
                print("To run without telemetry, use the --anonymous flag")
    def on_data(self, data):

        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)

        # # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
        # print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
        # print ''
        # return True

        sbs = ServiceBusService(service_namespace=config.servns,
                                shared_access_key_name=config.key_name,
                                shared_access_key_value=config.key_value)
        searched_tweets = "{ 'source': '" + unicode(
            decoded['user']['screen_name']) + "' , 'text': '" + unicode(
                decoded['text'].encode('ascii', 'ignore')) + "' }"
        print(unicode(searched_tweets))
        sbs.send_event('iot', unicode(searched_tweets))

        return True
Exemplo n.º 14
0
class azure_interface:
  def __init__(self, name_space, key_name, key_value, proxy = None):
    self.sbs = ServiceBusService(service_namespace=name_space,shared_access_key_name=key_name, shared_access_key_value=key_value)
    if proxy:
      self.sbs.set_proxy('proxy.iisc.ernet.in',3128)

  def event_send(self, hubname ,msg):
    try:
      hubStatus = self.sbs.send_event(hubname, str(msg))
      print "Send Status:", repr(hubStatus)
    except:
      print sys.exc_info()               
Exemplo n.º 15
0
    def insert_mock_logs_in_EventHub(self):
        print("Inserting fake logs in EventHub")
        namespace_name = self.get_eventhub_namespace()
        eventhub_name = 'insights-metrics-pt1m'
        defaultauthorule_name = "RootManageSharedAccessKey"

        eventhub_client = EventHubManagementClient(self.credentials,
                                                   self.subscription_id)

        ehkeys = eventhub_client.namespaces.list_keys(self.RESOURCE_GROUP_NAME,
                                                      namespace_name,
                                                      defaultauthorule_name)

        sbs = ServiceBusService(namespace_name,
                                shared_access_key_name=defaultauthorule_name,
                                shared_access_key_value=ehkeys.primary_key,
                                request_session=Session())
        mock_logs = json.load(open('metrics_fixtures.json'))
        print("inserting %s" % (mock_logs))
        sbs.send_event(eventhub_name, json.dumps(mock_logs))

        print("Event inserted")
    def insert_mock_logs_in_EventHub(self, filename):
        print("Inserting fake logs in EventHub")
        namespace_name = self.get_resource_name(
            self.event_hub_namespace_prefix, "Microsoft.EventHub/namespaces")

        defaultauthorule_name = "RootManageSharedAccessKey"

        eventhub_client = EventHubManagementClient(self.credentials,
                                                   self.subscription_id)

        ehkeys = eventhub_client.namespaces.list_keys(self.RESOURCE_GROUP_NAME,
                                                      namespace_name,
                                                      defaultauthorule_name)

        sbs = ServiceBusService(namespace_name,
                                shared_access_key_name=defaultauthorule_name,
                                shared_access_key_value=ehkeys.primary_key,
                                request_session=Session())
        mock_logs = json.load(open(filename))
        print("inserting %s" % (mock_logs))
        sbs.send_event(self.eventhub_name, json.dumps(mock_logs))

        print("Event inserted")
Exemplo n.º 17
0
class EventHubWriter(GenericWriter):
    """
    EventHubWriter sends all the events to Microsoft Azure Event Hub Service.
    """
    def __init__(self, eh_name, connection_string, format=None):
        from azure.servicebus import ServiceBusService
        """
        eh_name - Event Hub service name
        connection_string - Event Hub namespace connection string
        """
        conn_dict = {
            i.split('=', 1)[0]: i.split('=', 1)[1]
            for i in connection_string.split(';')
        }
        ns_name = conn_dict['Endpoint'].replace('sb://', '').replace(
            '.servicebus.windows.net/', '')
        self.__sbs__ = ServiceBusService(
            service_namespace=ns_name,
            shared_access_key_name=conn_dict['SharedAccessKeyName'],
            shared_access_key_value=conn_dict['SharedAccessKey'])
        self.__ehname__ = eh_name
        super(EventHubWriter, self).__init__(format=format)

    def send(self, event):
        #converting datetime timestamp to ISO 8601 format
        event['TimeStamp'] = event['TimeStamp'].isoformat() + "Z"
        try:
            self.__sbs__.send_event(self.__ehname__, self.Format.format(event))
        except:
            #adding small delay in case the there is temporary connection issue with Event Hub
            time.sleep(1)
            try:
                self.__sbs__.send_event(self.__ehname__,
                                        self.Format.format(event))
            except:
                raise IOError("Cannot send message to Event Hub service")
Exemplo n.º 18
0
if args.keyname is not None:
    ehSharedAccessKeyName = args.keyname  #RootManageSharedAccessKey
else:
    ehSharedAccessKeyName = os.environ['EH_SHARED_ACCESS_KEY_NAME']

if args.keyvalue is not None:
    ehSharedAccessKeyValue = args.keyvalue  #IdKZBJi4NXFkyCkPm2X2U3t6zJOPivMAm7WuQJCVGUw=
else:
    ehSharedAccessKeyValue = os.environ['EH_SHARED_ACCESS_KEY_VALUE']

sbs = ServiceBusService(service_namespace=ehNamespace,
                        shared_access_key_name=ehSharedAccessKeyName,
                        shared_access_key_value=ehSharedAccessKeyValue)
while (1 > -1):
    devices = []
    for x in range(0, 10):
        devices.append(str(uuid.uuid4()))

    for y in range(0, 20):
        #while (1>-1):
        for dev in devices:
            reading = {
                'id': str(uuid.uuid4()),
                'timestamp': str(datetime.datetime.utcnow()),
                'uv': random.random(),
                'temperature': random.randint(70, 100),
                'humidity': random.randint(70, 100)
            }
            s = json.dumps(reading)
            sbs.send_event(ehName, s)
    #    print y
Exemplo n.º 19
0
#Parameter aus dem uebergebenen Query lesen. Vorher pruefen, ob einer uebergeben wurde

if (len(sys.argv) > 1):
    print(sys.argv[1])
    tmpstring1 = sys.argv[1]
    tmpstring1 = tmpstring1.replace("OK", "")
    tmpstring = {}
    tmplist = tmpstring1.split("&")

    for part in tmplist:
        parts = part.split("=")
        tmpstring[parts[0]] = parts[1]
    tmpjson = json.dumps(tmpstring)
    print(tmpjson)
else:
    print('no arguments')
    sys.exit(0)

key_name = "Sender"
key_value = "kzfwcTmKws8qtAF1O8+XCzWb8E983mjyOw4v77W2QQc="

sbs = ServiceBusService("carObdHub",
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

while (True):
    print('sending...')
    sbs.send_event('myObdHub', tmpjson)
    print('sent!')
    sys.exit(0)
class ServiceBusEventHubTest(ServiceBusTestCase):

    def setUp(self):
        super(ServiceBusEventHubTest, self).setUp()

        self.sbs = ServiceBusService(
            self.settings.EVENTHUB_NAME,
            shared_access_key_name=self.settings.EVENTHUB_SAS_KEY_NAME,
            shared_access_key_value=self.settings.EVENTHUB_SAS_KEY_VALUE,
            request_session=Session(),
        )

        self._set_service_options(self.sbs, self.settings)

        self.event_hub_name = self.get_resource_name('uthub')

    def tearDown(self):
        if not self.is_playback():
            try:
                self.sbs.delete_event_hub(self.event_hub_name)
            except:
                pass

        return super(ServiceBusEventHubTest, self).tearDown()

    #--Helpers-----------------------------------------------------------------
    def _create_event_hub(self, hub_name):
        self.sbs.create_event_hub(hub_name, None, True)

    #--Test cases for event hubs ----------------------------------------------
    @record
    def test_create_event_hub_no_options(self):
        # Arrange

        # Act
        created = self.sbs.create_event_hub(self.event_hub_name)

        # Assert
        self.assertTrue(created)

    @record
    def test_create_event_hub_no_options_fail_on_exist(self):
        # Arrange

        # Act
        created = self.sbs.create_event_hub(self.event_hub_name, None, True)

        # Assert
        self.assertTrue(created)

    @record
    def test_create_event_hub_with_options(self):
        # Arrange

        # Act
        hub = EventHub()
        hub.message_retention_in_days = 5
        hub.status = 'Active'
        hub.user_metadata = 'hello world'
        hub.partition_count = 32
        created = self.sbs.create_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertTrue(created)
        created_hub = self.sbs.get_event_hub(self.event_hub_name)
        self.assertEqual(created_hub.name, self.event_hub_name)
        self.assertEqual(created_hub.message_retention_in_days,
                         hub.message_retention_in_days)
        self.assertEqual(created_hub.status, hub.status)
        self.assertEqual(created_hub.partition_count, hub.partition_count)
        self.assertEqual(created_hub.user_metadata, hub.user_metadata)
        self.assertEqual(len(created_hub.partition_ids), hub.partition_count)

    @record
    def test_create_event_hub_with_authorization(self):
        # Arrange

        # Act
        hub = EventHub()
        hub.authorization_rules.append(
            AuthorizationRule(
                claim_type='SharedAccessKey',
                claim_value='None',
                rights=['Manage', 'Send', 'Listen'],
                key_name='Key1',
                primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=',
                secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=',
            )
        )

        created = self.sbs.create_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertTrue(created)
        created_hub = self.sbs.get_event_hub(self.event_hub_name)
        self.assertEqual(created_hub.name, self.event_hub_name)
        self.assertEqual(len(created_hub.authorization_rules), 1)
        self.assertEqual(created_hub.authorization_rules[0].claim_type,
                         hub.authorization_rules[0].claim_type)
        self.assertEqual(created_hub.authorization_rules[0].claim_value,
                         hub.authorization_rules[0].claim_value)
        self.assertEqual(created_hub.authorization_rules[0].key_name,
                         hub.authorization_rules[0].key_name)
        self.assertEqual(created_hub.authorization_rules[0].primary_key,
                         hub.authorization_rules[0].primary_key)
        self.assertEqual(created_hub.authorization_rules[0].secondary_key,
                         hub.authorization_rules[0].secondary_key)

    @record
    def test_update_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        hub = EventHub(message_retention_in_days=3)
        result = self.sbs.update_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertIsNotNone(result)
        self.assertEqual(result.name, self.event_hub_name)
        self.assertEqual(result.message_retention_in_days,
                         hub.message_retention_in_days)

    @record
    def test_update_event_hub_with_authorization(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        hub = EventHub()
        hub.authorization_rules.append(
            AuthorizationRule(
                claim_type='SharedAccessKey',
                claim_value='None',
                rights=['Manage', 'Send', 'Listen'],
                key_name='Key1',
                primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=',
                secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=',
            )
        )
        result = self.sbs.update_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertIsNotNone(result)
        self.assertEqual(result.name, self.event_hub_name)
        self.assertEqual(len(result.authorization_rules), 1)
        self.assertEqual(result.authorization_rules[0].claim_type,
                         hub.authorization_rules[0].claim_type)
        self.assertEqual(result.authorization_rules[0].claim_value,
                         hub.authorization_rules[0].claim_value)
        self.assertEqual(result.authorization_rules[0].key_name,
                         hub.authorization_rules[0].key_name)
        self.assertEqual(result.authorization_rules[0].primary_key,
                         hub.authorization_rules[0].primary_key)
        self.assertEqual(result.authorization_rules[0].secondary_key,
                         hub.authorization_rules[0].secondary_key)

    @record
    def test_get_event_hub_with_existing_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        event_hub = self.sbs.get_event_hub(self.event_hub_name)

        # Assert
        self.assertIsNotNone(event_hub)
        self.assertEqual(event_hub.name, self.event_hub_name)

    @record
    def test_get_event_hub_with_non_existing_event_hub(self):
        # Arrange

        # Act
        with self.assertRaises(AzureServiceBusResourceNotFound):
            resp = self.sbs.get_event_hub(self.event_hub_name)

        # Assert

    @record
    def test_delete_event_hub_with_existing_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name)

        # Assert
        self.assertTrue(deleted)

    @record
    def test_delete_event_hub_with_existing_event_hub_fail_not_exist(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name, True)

        # Assert
        self.assertTrue(deleted)

    @record
    def test_delete_event_hub_with_non_existing_event_hub(self):
        # Arrange

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name)

        # Assert
        self.assertFalse(deleted)

    @record
    def test_delete_event_hub_with_non_existing_event_hub_fail_not_exist(self):
        # Arrange

        # Act
        with self.assertRaises(AzureMissingResourceHttpError):
            self.sbs.delete_event_hub(self.event_hub_name, True)

        # Assert

    @record
    def test_send_event(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        result = self.sbs.send_event(self.event_hub_name,
                                     'hello world')
        result = self.sbs.send_event(self.event_hub_name,
                                     'wake up world')
        result = self.sbs.send_event(self.event_hub_name,
                                     'goodbye!')

        # Assert
        self.assertIsNone(result)
Exemplo n.º 21
0
from httplib import HTTPConnection
from azure.servicebus import ServiceBusService


MCAST_GRP = '224.0.0.251'
MCAST_PORT = 6000

sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

# bind this to the master node's IP address
sock.setsockopt(SOL_IP, IP_ADD_MEMBERSHIP,
                inet_aton(MCAST_GRP)+inet_aton('10.0.0.1'))

sock.bind((MCAST_GRP, MCAST_PORT))
mreq = pack("4sl", inet_aton(MCAST_GRP), INADDR_ANY)
sock.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)

sbs = ServiceBusService(service_namespace='knockknockknock',
                        shared_access_key_name='RootManageSharedAccessKey',
                        shared_access_key_value=environ['ACCESS_KEY]')
sbs.create_event_hub('penny')

while True:
    data, srv_sock = sock.recvfrom(8192)
    srv_addr, srv_srcport = srv_sock[0], srv_sock[1]
    data = loads(data.replace('\0',''))
    data['srv_addr'] = srv_addr
    print data
    sbs.send_event('penny', unicode(dumps(data)))
Exemplo n.º 22
0
channel_list = [11, 12, 13, 15, 16, 18, 22, 29, 31, 33]
gpio.setup(channel_list, gpio.IN)

key_name = "SendRule"
key_value = "YEsTSbHUumqNJfnAr2O6Si0h/DIlblKpvJl3HJHFhiU="

sbs = ServiceBusService("smartwatering-ns",
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

event = {}
event['device_id'] = 1
event['value'] = 0

while (True):
    j = '0'
    j = j + str(gpio.input(11))
    j = j + str(gpio.input(12))
    j = j + str(gpio.input(13))
    j = j + str(gpio.input(15))
    j = j + str(gpio.input(16))
    j = j + str(gpio.input(18))
    j = j + str(gpio.input(22))
    j = j + str(gpio.input(29))
    j = j + str(gpio.input(31))
    j = j + str(gpio.input(33))
    value = int(j, 2)
    print(value)
    event['value'] = value
    sbs.send_event('smartwatering', json.dump(event))
Exemplo n.º 23
0
from azure.servicebus import ServiceBusService
import psutil

key_name = '<access_key_name>' # SharedAccessKeyName from Azure portal
key_value = '<access_key_value>' # SharedAccessKey from Azure portal
sb_namespace = '<namespace_name>'
sbs = ServiceBusService(service_namespace = sb_namespace,
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)
# sbs.create_event_hub('openalt')

count = 0;

while True:
    sbs.send_event('<eventhub_name>', '{ "MachineName":"Python-01", "CpuUsage":"'+str(psutil.cpu_percent())+'", "FreeMem":"" }')
    print(count)
    print('CpuUsage: '+str(psutil.cpu_percent()))
    count = count + 1
            [13, "Litter Box", "Pets", 30.00],
            [14, "Cough Syrup", "Medicine", 15.00]]
# --------------------------------------------------------
# --------------------------------------------------------
keepRunning = True
# This will run for about 2.5 hours which should be fine for labs and demos
for y in range(0, 2000):
    # Get a product from the products variable
    product = products[random.randint(0, 10)]
    # define a reading as a python dictionary object
    reading = {
        'storeId': storeids[random.randint(0, 10)],
        'timestamp': time.time(),
        'producttype': product[0],
        'name': product[1],
        'category': product[2],
        'price': product[3],
        'quantity': random.randint(1, 3)
    }

    # Add some intrigue...
    if product[1] == "Cough Syrup":
        reading['quantity'] += 10

    # use json.dumps to convert the dictionary to a JSON format
    s = json.dumps(reading)
    # send to Azure Event Hub
    sbs.send_event("ingestion", s)
    print(s)
    # wait 5 seconds
    time.sleep(5)
Exemplo n.º 25
0
import time
import sys
from azure.servicebus import ServiceBusService
import json

## Event hub ##
NamespaceName = "<add namespace name here>"
## Namespace is called "Endpoint" in Azure connection string.  ##
## From Namespace ignore "sb://" and "servicebus.windows.net/" ##

## Policy ##
## To the Event Hub create a new policy and use these keys for connection ##
SharedAccessKeyName="<add event hub policy name here>"
SharedAccessKey="<add policy key here>"
EntityPath="<add event hub name here>" # This is same as EventHub name with lower case letters

## Create service bus connection ##
sbs = ServiceBusService(NamespaceName,shared_access_key_name=SharedAccessKeyName, shared_access_key_value=SharedAccessKey)

## Test with sending some JSON data ##
print "Press Ctrl-C to quit."
i=1000
while(True):
    i += 1
    temp = {'DeviceId': "RaspberryPi", 'Temperature': float(i)}
    print temp
    sbs.send_event(EntityPath, json.dumps(temp))
    
    time.sleep(3)

Exemplo n.º 26
0
              pm10=sum(PM10) / float(len(PM10))
              NO2 = []
              CO =[]
              O3 =[]
              SO2 =[]
              PM1=[]
              PM2=[]
              PM10=[]
              message={"DeviceId":boardNo,"TIME":str(Time),"O3":str(o3),"SO2":str(so2),"NO2":str(no2),"CO":str(co),
                       "PM10":str(pm10),"PM1":str(pm1),"PM2.5":str(pm2),"LAT":str(Lat),"LONG":str(Lon),
                       'TEMP':str(Temp),'HUMID':str(Humidity),'SPEED':str(Speed),'CLIMB':str(Climb),
                       'HEAD':Head,'EPS':EPS, 'EPX':EPX,'EPV':EPV,'EPT':EPT,'ALT':Alt,
                       'BATV':BATV, 'BATI':BATI, 'BATP':BATP, 'SOLV':SOLV, 'SOLI':SOLI, 'SOLP':SOLP}
              print('Sending...')
              try:
                 sbs.send_event('daqs',json.dumps(message))
                 print('Sent!')
                 count+=1
                 print 'Packets sent since start:', count
                 print'Operating at',Temp, 'degrees celsius.'
                 print 'Location:', 'Lat', Lat, 'Lon', Lon, 'Alt', Alt
                 print 'Battery Info:', BATV, 'V', BATI, 'A', BATP, 'W'
                 print 'Solar Panel Info:', SOLV, 'V', SOLI, 'A', SOLP, 'W'

              except IOError or ConnectionError:
                 firstCycle=False
                 print ('ERROR. Did not send.')
except (KeyboardInterrupt, SystemExit): #End program when you press ctrl+c
      print ("\nEnding Thread...")
      gpsp.running = False
      alphasense.off()
class EventHubServiceTest(AzureTestCase):

    def setUp(self):
        self.sbs = ServiceBusService(
            credentials.getEventHubNamespace(),
            shared_access_key_name=credentials.getEventHubSasKeyName(),
            shared_access_key_value=credentials.getEventHubSasKeyValue(),
            )

        set_service_options(self.sbs)

        self.event_hub_name = getUniqueName('uthub')

    def tearDown(self):
        self.cleanup()
        return super(EventHubServiceTest, self).tearDown()

    def cleanup(self):
        try:
            self.sbs.delete_event_hub(self.event_hub_name)
        except:
            pass

    #--Helpers-----------------------------------------------------------------
    def _create_event_hub(self, hub_name):
        self.sbs.create_event_hub(hub_name, None, True)

    #--Test cases for event hubs ----------------------------------------------
    def test_create_event_hub_no_options(self):
        # Arrange

        # Act
        created = self.sbs.create_event_hub(self.event_hub_name)

        # Assert
        self.assertTrue(created)

    def test_create_event_hub_no_options_fail_on_exist(self):
        # Arrange

        # Act
        created = self.sbs.create_event_hub(self.event_hub_name, None, True)

        # Assert
        self.assertTrue(created)

    def test_create_event_hub_with_options(self):
        # Arrange

        # Act
        hub = EventHub()
        hub.message_retention_in_days = 5
        hub.status = 'Active'
        hub.user_metadata = 'hello world'
        hub.partition_count = 32
        created = self.sbs.create_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertTrue(created)
        created_hub = self.sbs.get_event_hub(self.event_hub_name)
        self.assertEqual(created_hub.name, self.event_hub_name)
        self.assertEqual(created_hub.message_retention_in_days,
                         hub.message_retention_in_days)
        self.assertEqual(created_hub.status, hub.status)
        self.assertEqual(created_hub.partition_count, hub.partition_count)
        self.assertEqual(created_hub.user_metadata, hub.user_metadata)
        self.assertEqual(len(created_hub.partition_ids), hub.partition_count)

    def test_create_event_hub_with_authorization(self):
        # Arrange

        # Act
        hub = EventHub()
        hub.authorization_rules.append(
            AuthorizationRule(
                claim_type='SharedAccessKey',
                claim_value='None',
                rights=['Manage', 'Send', 'Listen'],
                key_name='Key1',
                primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=',
                secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=',
            )
        )

        created = self.sbs.create_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertTrue(created)
        created_hub = self.sbs.get_event_hub(self.event_hub_name)
        self.assertEqual(created_hub.name, self.event_hub_name)
        self.assertEqual(len(created_hub.authorization_rules), 1)
        self.assertEqual(created_hub.authorization_rules[0].claim_type,
                         hub.authorization_rules[0].claim_type)
        self.assertEqual(created_hub.authorization_rules[0].claim_value,
                         hub.authorization_rules[0].claim_value)
        self.assertEqual(created_hub.authorization_rules[0].key_name,
                         hub.authorization_rules[0].key_name)
        self.assertEqual(created_hub.authorization_rules[0].primary_key,
                         hub.authorization_rules[0].primary_key)
        self.assertEqual(created_hub.authorization_rules[0].secondary_key,
                         hub.authorization_rules[0].secondary_key)

    def test_update_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        hub = EventHub(message_retention_in_days=3)
        result = self.sbs.update_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertIsNotNone(result)
        self.assertEqual(result.name, self.event_hub_name)
        self.assertEqual(result.message_retention_in_days,
                         hub.message_retention_in_days)

    def test_update_event_hub_with_authorization(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        hub = EventHub()
        hub.authorization_rules.append(
            AuthorizationRule(
                claim_type='SharedAccessKey',
                claim_value='None',
                rights=['Manage', 'Send', 'Listen'],
                key_name='Key1',
                primary_key='Wli4rewPGuEsLam95nQEwGR+e8b+ynlupZQ7VfjbQnw=',
                secondary_key='jS+lERPBmbBVGJ5JzIwVRtSGYoFUeunRoADNTjwU3jU=',
            )
        )
        result = self.sbs.update_event_hub(self.event_hub_name, hub)

        # Assert
        self.assertIsNotNone(result)
        self.assertEqual(result.name, self.event_hub_name)
        self.assertEqual(len(result.authorization_rules), 1)
        self.assertEqual(result.authorization_rules[0].claim_type,
                         hub.authorization_rules[0].claim_type)
        self.assertEqual(result.authorization_rules[0].claim_value,
                         hub.authorization_rules[0].claim_value)
        self.assertEqual(result.authorization_rules[0].key_name,
                         hub.authorization_rules[0].key_name)
        self.assertEqual(result.authorization_rules[0].primary_key,
                         hub.authorization_rules[0].primary_key)
        self.assertEqual(result.authorization_rules[0].secondary_key,
                         hub.authorization_rules[0].secondary_key)

    def test_get_event_hub_with_existing_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        event_hub = self.sbs.get_event_hub(self.event_hub_name)

        # Assert
        self.assertIsNotNone(event_hub)
        self.assertEqual(event_hub.name, self.event_hub_name)

    def test_get_event_hub_with_non_existing_event_hub(self):
        # Arrange

        # Act
        with self.assertRaises(WindowsAzureError):
            resp = self.sbs.get_event_hub(self.event_hub_name)

        # Assert

    def test_delete_event_hub_with_existing_event_hub(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name)

        # Assert
        self.assertTrue(deleted)

    def test_delete_event_hub_with_existing_event_hub_fail_not_exist(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name, True)

        # Assert
        self.assertTrue(deleted)

    def test_delete_event_hub_with_non_existing_event_hub(self):
        # Arrange

        # Act
        deleted = self.sbs.delete_event_hub(self.event_hub_name)

        # Assert
        self.assertFalse(deleted)

    def test_delete_event_hub_with_non_existing_event_hub_fail_not_exist(self):
        # Arrange

        # Act
        with self.assertRaises(WindowsAzureError):
            self.sbs.delete_event_hub(self.event_hub_name, True)

        # Assert

    def test_send_event(self):
        # Arrange
        self._create_event_hub(self.event_hub_name)

        # Act
        result = self.sbs.send_event(self.event_hub_name,
                                     'hello world')
        result = self.sbs.send_event(self.event_hub_name,
                                     'wake up world')
        result = self.sbs.send_event(self.event_hub_name,
                                     'goodbye!')

        # Assert
        self.assertIsNone(result)
Exemplo n.º 28
0
gpio.setmode(gpio.BOARD)
channel_list=[11,12,13,15,16,18,22,29,31,33]
gpio.setup(channel_list,gpio.IN)

key_name = "SendRule"
key_value = "YEsTSbHUumqNJfnAr2O6Si0h/DIlblKpvJl3HJHFhiU="

sbs = ServiceBusService("smartwatering-ns",shared_access_key_name=key_name,shared_access_key_value=key_value)

event={}
event['device_id']=1
event['value']=0

while (True):
    j='0'
    j=j+str(gpio.input(11))
    j=j+str(gpio.input(12))
    j=j+str(gpio.input(13))
    j=j+str(gpio.input(15))
    j=j+str(gpio.input(16))
    j=j+str(gpio.input(18))
    j=j+str(gpio.input(22))
    j=j+str(gpio.input(29))
    j=j+str(gpio.input(31))
    j=j+str(gpio.input(33))
    value=int(j,2)
    print(value)
    event['value']=value
    sbs.send_event('smartwatering',json.dump(event))
# -*- coding: utf-8 -*-
#
# install pre-requisite package
# pip install azure-servicebus
#

import json
from azure.servicebus import ServiceBusService

eventhub_namespace="<Eventhub Top Level Namespace>"
entity= "<Eventhub Entity Name>"
sasKeyName = "<SAS Policy Name>"
sasKeyValue= "<SAS Key Value>"

sbs = ServiceBusService(eventhub_namespace, shared_access_key_name=sasKeyName, shared_access_key_value=sasKeyValue)
message = {
    "deviceId": "myDevice001",
    "temperature": "13.5" 
    }
sbs.send_event(entity, json.dumps(message))
    lines = read_temp_raw(dfile)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw(dfile)
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c
host = socket.gethostname()

while True:
    try:
        temp1 = read_temp(device1_file)
        temp2 = read_temp(device2_file)
        body = '{\"DeviceId\": \"' + host + '\" '
        now = datetime.now()
        body += ', \"rowid\":' + now.strftime('%Y%m%d%H%M%S')
        body += ', \"Time\":\"' + now.strftime('%Y/%m/%d %H:%M:%S') + '\"'
        body += ', \"Temp1\":' + str(temp1)
        body += ', \"Temp2\":' + str(temp2) + '}'
        print body
        sbs = ServiceBusService(service_namespace=name_space,shared_access_key_name=key_name, shared_access_key_value=key_value)
        hubStatus = sbs.send_event('sensordemohub',body)

        print "Send Status:", repr(hubStatus)
        time.sleep(5)
    except Exception as e:
        print "Exception - ",
repr(e)
from azure.servicebus import ServiceBusService
import json


servns = 'Miage2016' # service_bus _namespace
key_name = 'manage'  # SharedAccessKeyName from Azure portal
key_value = 'KEOU/Qun1wrPFO8eLXM4HCEa59WDP2qLcuuhNapYEjQ='  # SharedAccessKey from Azure portal
cpt = 0
sbs = ServiceBusService(service_namespace=servns,
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value) # Create a ServiceBus Service Object

with open('telco.json') as f:
    o=json.load(f)

from time import sleep
for e in o :
    print(json.dumps(e))
    cpt = cpt + 1
    sbs.send_event('iot', json.dumps(e))
    sleep(1)
print(cpt)
print("Finished")
Exemplo n.º 32
0
import time
import sys
from azure.servicebus import ServiceBusService


key_name = "MySender"
key_value = "MyKeyGoesHere"

sbs = ServiceBusService("robotdeskeventhub-ns",shared_access_key_name=key_name, shared_access_key_value=key_value)

while(True):
	print('sending...')
	sbs.send_event('nameofeventhub', '{ "DeviceId": "smokerpi", "Temperature": "37.0" }')
	print('sent!')
	time.sleep(10)
	
	

import time
import sys
from azure.servicebus import ServiceBusService

infile = open("tempOutput.txt", "r")
temp = infile.readline().rstrip()
#print('received temp of: ' + temp)
temp = int(temp)

key_name = "sendRule"
key_value = "9SWS0sNEBQMfTmuBHlxFwUHBFMSBgmJ77/ICSRm9HK4="

sbs = ServiceBusService("pimessage-ns",shared_access_key_name=key_name, shared_access_key_value=key_value)
if temp > 65 or temp < 30:
#    print('sending temp of:' + temp)
    sbs.send_event('pimessage', '{ "DeviceId": "smokerpi", "Temperature": temp }')
    print('sent!')
    print ('got here')
else:
    print('temp was in normal range')
            [13, "Litter Box", "Pets", 30.00],
            [14, "Cough Syrup", "Medicine", 15.00]]
# --------------------------------------------------------
# --------------------------------------------------------

# This will run for about 2.5 hours which should be fine for labs and demos
for y in range(0, 2000):
    # Get a product from the products variable
    product = products[random.randint(0, 10)]
    # define a reading as a python dictionary object
    reading = {
        'storeId': storeids[random.randint(0, 10)],
        'timestamp': time.time(),
        'producttype': product[0],
        'name': product[1],
        'category': product[2],
        'price': product[3],
        'quantity': random.randint(1, 3)
    }

    # Add some intrigue...
    if product[1] == "Cough Syrup":
        reading['quantity'] += 150

    # use json.dumps to convert the dictionary to a JSON format
    s = json.dumps(reading)
    # send to Azure Event Hub
    sbs.send_event("<hub-name>", s)
    print(s)
    # wait 5 seconds
    time.sleep(5)
Exemplo n.º 35
0
# GrovePi + Grove Temperature Sensor
import time
import grovepi
from azure.servicebus import ServiceBusService

key_name ='RootManageSharedAccessKey' # SharedAccessKeyName from Azure Portal
key_value='' # SharedAccessKey from Azure Portal
sbs = ServiceBusService('asatestsn', shared_access_key_name=key_name, shared_access_key_value=key_value)
sbs.create_event_hub('hubcreationfromlinux')

# Connect the Grove Temperature Sensor to analog port D4
sensor_port = 4
deviceId = "device-1"
#Declare direction to the pin.
#grovepi.pinMode (Temp_sensor,"INPUT")
while True:
    try:
        [temp,hum] = grovepi.dht(sensor_port,0)
        CurrentTime = str(time.localtime(time.time()).tm_hour) + ":" + str(time.localtime(time.time()).tm_min) + ":"+ str(time.localtime(time.time()).tm_sec)
        print "Temperature : ", temp , "Humidity : ", hum, "RecordTime : ", CurrentTime  
        sbs.send_event('hubcreationfromlinux', '{ "DeviceId":"' + deviceId + '", "Temperature":"' + str(temp) +'", "Humidity":"' + str(hum) +'", "RecordTime":"' + str(CurrentTime) +'"}')
        # sbs.send_event('hubcreationfromlinux', '{ "DeviceId":"' + deviceId + '", "Temperature":"' + temperature +'"}')
        time.sleep(1.0)
    except IOError:
        print "Error"
 if isfirstrun == 1 :
     if isfirstrunRepeat == 1 :
         thisRunWaterMark=timecreated
         isfirstrunRepeat=0
     #greedy run first
     outfile = open("last_time_processed", "w")
     outfile.write(thisRunWaterMark.strftime("%Y-%m-%dT%H:%M:%S"))
     outfile.close()
     #run until end 
     if 'reverse mapping checking getaddrinfo for' in text:
      count+=1 
      dns= text.split('for ')[1].split(' [')[0]
      ip= text.split('for ')[1].split(' failed')[0].split('[')[1].split(']')[0]
      messagetosend = '{"guid":"62X74059-A444-4797-8A7E-526C3EF9D64B","organization":"SG MIC","timecreated":"'+timecreated.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")+'","displayname":"SSH Sensor","location":"Azure DC Singapore","measurename":"SSH Reverse Mapping","unitofmeasure":"count","value":1,"dns":"'+dns+'","ip":"'+ip+'"}'
      print('sending event at ' +messagetosend)
      sbs.send_event('ehdevices', messagetosend)
      
     elif 'Failed password for root' in text:
      count+=1 
      ip= text.split('from ')[1].split(' port')[0]
      port= text.split('port ')[1].split(' ssh')[0]
      messagetosend = '{"guid":"62X74059-A444-4797-8A7E-526C3EF9D64B","organization":"SG MIC","timecreated":"'+timecreated.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")+'","displayname":"SSH Sensor","location":"Azure DC Singapore","measurename":"SSH Failed Login Attempt","unitofmeasure":"count","value":1,"port":"'+port+'","ip":"'+ip+'"}'
      print('sending event at ' +messagetosend)
      sbs.send_event('ehdevices', messagetosend)
     elif 'Failed password for invalid user' in text:
      count+=1 
      ip= text.split('from ')[1].split(' port')[0]
      port= text.split('port ')[1].split(' ssh')[0]
      user = text.split('user ')[1].split(' from')[0]
      messagetosend = '{"guid":"62X74059-A444-4797-8A7E-526C3EF9D64B","organization":"SG MIC","timecreated":"'+timecreated.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")+'","displayname":"SSH Sensor","location":"Azure DC Singapore","measurename":"SSH Failed Login Attempt","unitofmeasure":"count","value":1,"port":"'+port+'","ip":"'+ip+'","user":"******"}'
      print('sending event at ' +messagetosend)
Exemplo n.º 37
0
import json
import csv
import random
import time

service_namespace = "<NAMESPACE_NAME>"
shared_access_key_name = "RootManageSharedAccessKey"
shared_access_key_value = "<KEY_VALUE>"

sbs = ServiceBusService(service_namespace,
                        shared_access_key_name=shared_access_key_name,
                        shared_access_key_value=shared_access_key_value)


def genMessage ():
    message = {
        "id": random.randint(1000,100000),
        "tt_1": random.randint(0, 100),
        "record": random.randint(0,3),
        "ts": time.time()

    }
    jsonMessage = json.dumps(message)
    return jsonMessage

for i in range(1, 10000):
	message = genMessage()
	sbs.send_event("<HUB_NAME>", message)
	print(message)

Exemplo n.º 38
0
            }
            # append the product generated in readingJson to productsInTransaction array
            productsInTransaction.append(readingJson)
        # append an array of product jsons generated aboce to the overall transactions list
        transactions.append(productsInTransaction)
        # increment id start to get new ID number for transaction id construction
        transactionIDStart += 1

    if kafka == False:
        # for each transaction generated
        for transaction in transactions:
            # for each product in each transaction
            for reading in transaction:
                # use json.dumps to convert the dictionary to a JSON format
                s = json.dumps(reading)
                # send to Azure Event Hub
                sbs.send_event(EVENT_HUB_NAME, s)
                print(s)
    else:
        # for each transaction generated
        for transaction in transactions:
            # for each product in each transaction
            for reading in transaction:
                s = json.dumps(reading)
                producer.send(TOPIC_NAME, s)
                print(s)
    # delay a second
    time.sleep(1)
    # add secodn to timestamp
    timeStamp += 1
Exemplo n.º 39
0
key_value = ""
event_hub_namespace = ""
event_hub_name = ""

sbs = ServiceBusService(service_namespace=event_hub_namespace,
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

while True:
    sleep(0.5)
    soundLevel = grovepi.analogRead(sound_sensor)

    sleep(0.5)
    lightLevel = grovepi.analogRead(light_sensor)

    sleep(0.5)
    distance = ultrasonicRead(ultrasonic_ranger)

    sleep(0.3)
    [temp, hum] = dht(dht_sensor_port, dht_sensor_type)

    t = str(temp)
    h = str(hum)

    dataPoint = DataPoint(t, h, soundLevel, lightLevel, distance)

    payload = json.dumps(dataPoint, default=encode_data)
    print(payload)

    sbs.send_event(event_hub_name, payload)
    print("sending....")
Exemplo n.º 40
0
from azure.servicebus import ServiceBusService

NAMESPACE = 'chen-test-eh'
KEY = 'ifs5GUcqdBANX8kh5T2DuwXrd6Qfhz1M5MaBtFIyLLY='
EVENTHUB = 'test_cap'

sbs = ServiceBusService(service_namespace=NAMESPACE,
                        shared_access_key_name='RootManageSharedAccessKey',
                        shared_access_key_value=KEY,
                        host_base='.servicebus.chinacloudapi.cn')
devices = []
for x in range(0, 10):
    devices.append(str(uuid.uuid4()))

for y in range(0, 20000):
    for dev in devices:
        reading = {
            'id': dev,
            'timestamp': str(datetime.datetime.utcnow()),
            'uv': random.random(),
            'temperature': random.randint(70, 100),
            'humidity': random.randint(70, 100)
        }
        s = json.dumps(reading)
        sbs.send_event(EVENTHUB, s)
    print(y)

# for y in range(0,200):
#    s='hello '*random.randint(1,10) + 'world '*random.randint(1,10)
#    sbs.send_event(EVENTHUB, s)
Exemplo n.º 41
0
def signal(secs):
    led.write(0)
    time.sleep(secs)
    led.write(1)

signal(1)

#even hub config
sbs = ServiceBusService("myhubed-ns",
                        shared_access_key_name="SendReceiveRule",
                        shared_access_key_value="hGRlK8cfxw/nU0SoH/egwJbg33BiUAi

def logging():
    cells = Cell.all('wlan0')
    count = len(cells)
    sbs.send_event('myhub',  json.dumps("Count: " + str(count)))
    print "Count: " + str(count)
    for i in range(count):
        message = "SSID: " + cells[i].ssid + ", Signal: " + str(cells[i].signal)
        sbs.send_event('myhub',  json.dumps(message))
        print message
    signal(1)
    print "Done"
	
# Listen for incoming connections
sock.listen(5)
print "Connection opened..."

while True:
    try:
        # Wait for a connection
Exemplo n.º 42
0
import json
import datetime
from grovepi import *
from azure.servicebus import ServiceBusService


dht_sensor_port = 6             # Connect the DHt sensor to this port 
dht_sensor_type = 0             # change this depending on your sensor type - see header comment
potentiometer=0                 # test device on Analog Port i.e. poti ...


sbs = ServiceBusService(service_namespace='STITlndf-ns', shared_access_key_name='sendPOLICY', shared_access_key_value='Yil7vtCJx1HwxKXq7F3xDN+sbMUT4nud6QRRqItuxL4=')

while True:
    try:
        [ temp,hum ] = dht(dht_sensor_port,dht_sensor_type)     #Get the temperature and Humidity from the DHT sensor
        if not math.isnan(temp):
            if not math.isnan(hum):
                #itemp=analogRead(potentiometer)
                #temp= itemp
                #hum=itemp
                t = str(temp)
                h = str(hum)
                jsn = {'DeviceId': 'room1', 'Temperature': t, 'Humidity': h}
                print jsn, ' ', datetime.datetime.now()
                sbs.send_event('stitlndf',json.dumps(jsn) )
        
    except (IOError,TypeError) as e:
        print 'Error'

import datetime
import random
import json
import time
from azure.servicebus import ServiceBusService

sbs = ServiceBusService(service_namespace='<event hubs namespace>',
                        shared_access_key_name='<key name>',
                        shared_access_key_value='<key value>')
devices = []
for x in range(0, 10):
    devices.append(str(uuid.uuid4()))
cities = [
    'Chicago', 'New York City', 'Los Angeles', 'London', 'Salt Lake City',
    'Dallas'
]
for y in range(0, 2000):
    for dev in devices:
        reading = {
            'id': dev,
            'timestamp': str(datetime.datetime.utcnow()),
            'uv': random.random(),
            'temperature': random.randint(70, 100),
            'humidity': random.randint(70, 100),
            'city': cities[random.randint(0, 4)]
        }
        s = json.dumps(reading)
        sbs.send_event('samplehub', s)
    print(y)
    print(reading)
    time.sleep(5)
Exemplo n.º 44
0
import random

with open("settings.json") as json_file:
    api_key = json.load(json_file) 

sbs = ServiceBusService(api_key["namespace"],
                        shared_access_key_name=api_key["policy_name"],
                        shared_access_key_value=api_key["policy_secret"])


for i in range(100):
    roomtemp = random.randint(60, 70)

    dev1 = random.randint(1, 10)
    temp = {'DeviceId': 'device-1', 'Temperature': str(dev1), 'RoomTemperature': str(roomtemp)}
    sbs.send_event('woodstove2', json.dumps(temp))
    print(json.dumps(temp))

    dev2 = random.randint(20, 30)
    temp = {'DeviceId': 'device-2', 'Temperature': str(dev2), 'RoomTemperature': str(roomtemp)}
    sbs.send_event('woodstove2', json.dumps(temp))
    print(json.dumps(temp))

    dev3 = random.randint(30, 40)
    temp = {'DeviceId': 'device-3', 'Temperature': str(dev3), 'RoomTemperature': str(roomtemp)}
    sbs.send_event('woodstove2', json.dumps(temp))
    print(json.dumps(temp))

    dev4 = random.randint(40, 50)
    temp = {'DeviceId': 'device-4', 'Temperature': str(dev4), 'RoomTemperature': str(roomtemp)}
    sbs.send_event('woodstove2', json.dumps(temp))
Exemplo n.º 45
0
import time
import sys
from azure.servicebus import ServiceBusService

infile = open("tempOutput.txt", "r")
temp = infile.readline().rstrip()
#print('received temp of: ' + temp)
temp = int(temp)

key_name = "sendRule"
key_value = "9SWS0sNEBQMfTmuBHlxFwUHBFMSBgmJ77/ICSRm9HK4="

sbs = ServiceBusService("pimessage-ns",
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)
if temp > 65 or temp < 30:
    #    print('sending temp of:' + temp)
    sbs.send_event('pimessage',
                   '{ "DeviceId": "smokerpi", "Temperature": temp }')
    print('sent!')
    print('got here')
else:
    print('temp was in normal range')
Exemplo n.º 46
0
def eh_send_func(sbnamespace, ehname, sasname, saskey):
    sbs = ServiceBusService(sbnamespace,
                            shared_access_key_name=sasname,
                            shared_access_key_value=saskey)

    return lambda producertoken, encodedmsg: sbs.send_event(ehname, encodedmsg, device_id=producertoken)
Exemplo n.º 47
0
def send_events_to_event_hub(p_message):
    sbs = ServiceBusService("mtrpocehns",
                            shared_access_key_name="RootManageSharedAccessKey",
                            shared_access_key_value=shared_access_key_eh)

    sbs.send_event('mtrtransactionseh', p_message)
Exemplo n.º 48
0
tenant = '1'
num_devices = 10
shared_access_key_value = '#REPLACEME'
shared_access_key_name = 'RootManageSharedAccessKey'
service_namespace = '#REPLACEME'
sbs = ServiceBusService(service_namespace,
                        shared_access_key_name=shared_access_key_name,
                        shared_access_key_value=shared_access_key_value)
hub_name = 'tenant' + tenant

while True:
    try:
        msg = {}
        is_error = choice([True, False])
        device_id = randrange(1, num_devices)
        temperature = randrange(-50, 50) + random()
        pressure = randrange(0, 500) + random()
        ts = datetime.now().isoformat()
        msg["deviceId"] = "tenant" + tenant + "-" + str(device_id)
        msg["temperature"] = temperature
        if not is_error:
            msg["pressure"] = pressure
        msg["ts"] = ts
        msg["source"] = "eventhub"

        print(json.dumps(msg))
        sbs.send_event(hub_name, json.dumps(msg))
        time.sleep(0.01)
    except Exception as e:
        print(e)
Exemplo n.º 49
0
      arg_query = arg
   elif opt == '-t':
      arg_time = float(arg)

# if arg_query == '':
tweet_id = arg_tweet_id
while True:
	i = 0
	for status in tweepy.Cursor(api.home_timeline, since_id = tweet_id).items(max_tweets):
		if i == 0:
			last_tweet_id = status.id
		# print(unicode(status.text))
		print("tweet : " + str(status.id))
		searched_tweets = "{ 'source': '" + unicode(status.user.name) + "' , 'text': '" + unicode(status.text) + "' }"
		print(unicode(searched_tweets))
		sbs.send_event('iot', unicode(searched_tweets))
		i = i + 1

	tweet_id = last_tweet_id
	print('dodo' + ' id : ' + str(last_tweet_id))
	sleep(arg_time)

# else:
# searched_tweets = [status._json for status in tweepy.Cursor(api.home_timeline).items(max_tweets)]
# searched_tweets = json.dumps(searched_tweets)
# sbs.send_event('iot', searched_tweets)

# for result in tweepy.Cursor(api.search, q=query).items():
#     sbs.send_event('iot', result)
#     sleep(1)
Exemplo n.º 50
0
#!/usr/bin/python3
import requests
import datetime
import random
import json
from azure.servicebus import ServiceBusService
creds=json.load(open('/home/chaos/password.json'))
armageddon=json.load(open('/home/chaos/armageddon.json'))

if not armageddon['state']:
    sbs = ServiceBusService(service_namespace='chaosMonkeys', shared_access_key_name='RootManageSharedAccessKey', shared_access_key_value=creds['password'])

    min_level=5.656
    max_level=13.563
    cl=json.load(open('/home/chaos/tank_stat.json','r'))

    row= {'name':'StackTank', 'Timestamp':datetime.datetime.now().isoformat(), 'location':{'lat':36.116626,'long':-97.709833},'max':max_level}
    cl['level']+=(random.random()/10)    
    if cl['level']>max_level:
        cl['level']=min_level
    row['level']=cl['level']
    json.dump(cl,open('/home/chaos/tank_stat.json','w'))
    sbs.send_event('tanklevel', json.dumps(row))
def lambda_handler(event, context):

    key_name = "awscollector"
    #key_value = os.environ.get('EMF_KEY_VALUE')
    key_value = "1gsvM56NH02r1qhLs/czbjdjNqEnVnqwi4GZNn20b2s="
    service_namespace = "em-lab-ns-intake01"
    sbs = ServiceBusService(service_namespace,
                            shared_access_key_name=key_name,
                            shared_access_key_value=key_value,
                            timeout=30)

    sql = ''\
    'SELECT blocked_locks.pid     AS blocked_pid, '\
           'blocked_activity.usename  AS blocked_user, '\
           'blocking_locks.pid     AS blocking_pid, '\
           'blocking_activity.usename AS blocking_user, '\
           'blocked_activity.query    AS blocked_statement, '\
           'blocking_activity.query   AS current_statement_in_blocking_process '\
     'FROM  pg_catalog.pg_locks         blocked_locks '\
      'JOIN pg_catalog.pg_stat_activity blocked_activity  ON blocked_activity.pid = blocked_locks.pid '\
      'JOIN pg_catalog.pg_locks         blocking_locks  '\
          'ON blocking_locks.locktype = blocked_locks.locktype '\
          'AND blocking_locks.DATABASE IS NOT DISTINCT FROM blocked_locks.DATABASE '\
          'AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation '\
          'AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page '\
          'AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple '\
          'AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid '\
          'AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid '\
          'AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid '\
          'AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid '\
          'AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid '\
          'AND blocking_locks.pid != blocked_locks.pid '\
      'JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid '\
     'WHERE NOT blocked_locks.GRANTED'

    logger.info("SQL:  " + str(sql))

    cur = conn.cursor()
    cur.execute(sql)
    item_count = 0
    for row in cur:
        #do something with every single row here
        #optionally print the row
        print row
        logger.info("Message: " + str(row))
        if item_count < 1:
            event_out = {}
            event_out['Source'] = 'RDS Lambda Alarm'
            event_out['Host'] = rds_host
            event_out['EventType'] = 'RDS Postgres blocking locks'
            event_out[
                'Summary'] = 'This is fired when there is blocking happening in the Postgresql'
            event_out['Severity'] = 0
            #event_out['ExtraDetails'] = 'Blocked: ' + row.blocked_statement + ' Blocking: ' + row.current_statement_in_blocking_process + '\n'
            event_out['ExtraDetails'] = row
            event_out['emf_id'] = str(uuid.uuid4())
            event_out['source_instance'] = db_name
        else:
            event_out['ExtraDetails'] = event_out['ExtraDetails'] + row
        item_count += 1
    if item_count > 0:
        sbs.send_event('lab-eh-aws-intake', json.dumps(event_out))
        logger.info("Message: " + str(event_out))

    return "Added %d items from RDS Postgresql table"
Exemplo n.º 52
0
import time
import sys
from azure.servicebus import ServiceBusService

key_name = "MySender"
key_value = "MyKeyGoesHere"

sbs = ServiceBusService("robotdeskeventhub-ns",
                        shared_access_key_name=key_name,
                        shared_access_key_value=key_value)

while (True):
    print('sending...')
    sbs.send_event('nameofeventhub',
                   '{ "DeviceId": "smokerpi", "Temperature": "37.0" }')
    print('sent!')
    time.sleep(10)
Exemplo n.º 53
0
import uuid
import datetime
import random
import json
from azure.servicebus import ServiceBusService

sbs = ServiceBusService(service_namespace='cpvevh1', shared_access_key_name='first', shared_access_key_value='WZnrLkWdsWCDehbO5OAUEGIVXpiE+V9Yn9CZqGX/gMs=')
devices = []
for x in range(0, 10):
    devices.append(str(uuid.uuid4()))

for y in range(0,20):
    for dev in devices:
        reading = {'id': dev, 'timestamp': str(datetime.datetime.utcnow()), 'uv': random.random(), 'temperature': random.randint(70, 100), 'humidity': random.randint(70, 100)}
        s = json.dumps(reading)
        sbs.send_event('ev1', s)
    print(y)