1 2 Previous Next 18 Replies Latest reply on Jul 14, 2019 8:56 PM by sabari yadavilli

    Create an event in TrueSight using a REST call from PowerShell.

    Peter Kofoed
      Share:|

      Does anyone have an example of how to create an event in TrueSight using a REST call from PowerShell.

      I would like an example of both how to get an authenticate token and how to generate an event

        • 1. Re: Create an event in TrueSight using a REST call from PowerShell.
          Patrick Mischler

          Hi Peter

           

          Yes, you can do that:

          Invoke-RestMethod -Method Post -Uri ${tsProtocol}://${tsServer}:${tsPort}/bppmws/api/Event/create?routingId=${tsCell}'&'routingId=CELL_NAME -Headers @{Authorization=("Basic {0}" -f $tsAuth); tenantName="BmcRealm"} -ContentType application/json -Body $jsonEvent -OutFile "D:\Temp\wrout.txt"

           

          You have to create a JSON structure for the event:

           

          $jsonEvent = @(@{

                          eventSourceHostName = $hostName;

                          eventSourceIPAddress = $ip;

                          attributes = @{

                              CLASS = $class;

                              mc_object_class = $objectClass;

                              mc_object = $object;

                              mc_parameter = $param;

                              msg = $msg;

                              severity = $severity;

                              priority = $priority;

                          }

                      }) | convertTo-Json -Depth 3

           

          Of course you have to define all the variables.

           

          I have shared a PowerShell Script with you. I think you have to do some adjustment so that it fits in your environment.

           

          Regards,

          Patrick

          2 of 2 people found this helpful
          • 2. Re: Create an event in TrueSight using a REST call from PowerShell.
            Peter Kofoed

            I get this response:

            Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

            At line:1 char:1

            + Invoke-RestMethod -Method Post -Uri ${tsProtocol}://${tsServer}:${tsPort}/bppmws ...

            + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException

                + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

             

            I am not sure if I set $tsAuth correct.

            I have used this method:

            $tsAuth = (Invoke-RestMethod -Method Post -Uri  https://${tsps}/tsws/10.0/api/authenticate/login -ContentType application/json -Body '{"username":"user...", "password":"psw...", "tenantName":"BmcRealm"}' | select -ExpandProperty response).authtoken

             

            $tsAuth works in Postman and curl if I add "authToken " in front of it.

            • 3. Re: Create an event in TrueSight using a REST call from PowerShell.
              Patrick Mischler

              Hi Peter

               

              You have to base64 encode the clear text passwort. This is not the authToken generated by the login rest call.

               

              Regards,

              Patrick

              • 4. Re: Create an event in TrueSight using a REST call from PowerShell.
                Charles Kelley

                Here is a simple example (simple, especially since the password is just plaintext below)

                 

                [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $True }

                 

                $tsimserver = "hostname_here"

                $cellname = "cellname_here"

                 

                $loginurl = "http://${tsimserver}/bppmws/api/authenticate/login"

                 

                $body = @{

                    username = "admin"

                    password = "type_password_here"

                tenantName = "BmcRealm"

                }

                 

                $login = Invoke-RestMethod -Method Post -Uri $loginurl -Body $body

                 

                 

                $authToken = $login.response.authToken

                $headers = @{ Authorization = "authToken $authToken" }

                $eventurl = "http://${tsimserver}/bppmws/api/Event/create?routingId=${cellname}&routingIdType=CELL_NAME"

                $eventbody = '[{

                "eventSourceHostName": "bppmwsserver1.domain.com",

                "eventSourceIPAddress": "192.72.255.151",

                "attributes": {

                "CLASS": "EVENT",

                "severity": "WARNING",

                "msg": "This is a simple test from PowerShell",

                "mc_smc_alias": "Prod application SRV1",

                "mc_smc_id": "Model1_10000_S0109",

                "mc_owner": "Peter",

                "mc_priority": "PRIORITY_4"

                }

                }]'

                 

                $sendevent = Invoke-RestMethod -Method Post -Headers $headers -Uri $eventurl -Body $eventbody -ContentType "application/json"

                2 of 2 people found this helpful
                • 5. Re: Create an event in TrueSight using a REST call from PowerShell.
                  Charles Kelley

                  If you want to use basic authentication (base64 encoded value of username:password) instead of an authToken, here is a command to set that to a variable:

                   

                  $myvar = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("username_here:password_here"))

                  1 of 1 people found this helpful
                  • 6. Re: Create an event in TrueSight using a REST call from PowerShell.
                    Peter Kofoed

                    Thanks I am able to make both methods working

                    • 7. Re: Create an event in TrueSight using a REST call from PowerShell.
                      Vadivel Paramesh

                      Hi Charles,

                      By any chance, do you have this script in shell or python to use in linux environment?

                      With kind regards

                      Vels

                      • 8. Re: Create an event in TrueSight using a REST call from PowerShell.
                        Vadivel Paramesh

                        Hi Peter,

                        Do you have the script that works with xxx-urlencoded authentication method as well?

                        Regards

                        Vels

                        • 9. Re: Create an event in TrueSight using a REST call from PowerShell.
                          Brendan Murray

                          Hi Vels,

                           

                          Here's a Python script to create an event. It is heavily commented to help you understand what it's doing.

                           

                          #!/usr/bin/python

                          # create_event.py

                          # Version 1.1

                          # Written using Python 2.7.15

                          # Creates an event in TSOM.

                          #

                          # Copyright BMC Software, 2019.

                          # Last modified: 02-Apr-19

                           

                          # Import required modules

                          # Note that the requests module will have to be installed,

                          # as it is not part of the standard Python package.

                           

                          import json

                          import requests

                          from requests.packages.urllib3.exceptions import InsecureRequestWarning

                          requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

                           

                          # Define global variables to hold host names.

                          tsim_host = 'FQDN of your TSIM server'

                          tsps_host = 'FQDN of your Presentation Server'

                           

                          # TSOM credentials and tenant information.

                          tsom_user = 'my_user_id'

                          tsom_pwd = 'my_pwd'

                          tsom_tenant = '*'

                           

                          def define_event():

                           

                            # Create a dictionary to hold the attributes for the event.

                            # Be sure to use valid slot names as the keys.

                            event_data = {}

                            event_data['severity'] = 'WARNING'

                            event_data['CLASS'] = 'EVENT'

                            event_data['msg'] = 'This event was created using the TSOM REST API'

                            event_data['mc_host'] = 'myhost.megacorp.com'

                           

                            # The TSOM create event call expects a list of events,

                            # even for just a single event.

                            event_list = []

                           

                            # Define the dictionary that wraps each event.

                            event_wrapper = {}

                           

                            event_wrapper['eventSourceHostName'] = 'myhost.megacorp.com'

                            event_wrapper['attributes'] = event_data

                           

                            # Add the event to the list

                            event_list.append(event_wrapper)

                           

                            # Convert event data to the JSON format required by the API.

                            json_data = json.dumps(event_list)

                           

                            return json_data

                           

                          def get_authToken():

                           

                            url = 'https://' + tsps_host + '/tsws/10.0/api/authenticate/login'

                            

                            # Create a dictionary for the request body

                            request_body = {}

                            request_body['username'] = tsom_user

                            request_body['password'] = tsom_pwd

                            request_body['tenantName'] = tsom_tenant

                           

                            # Load the request body into the payload in JSON format.

                            payload = json.dumps(request_body)

                           

                            headers = {

                                'content-type': "application/json",

                                'cache-control': "no-cache",

                            }

                           

                            # Execute the API call.

                            response = requests.post(url, data=payload, headers=headers, verify=False)

                           

                            # Capture the authentication token

                            if (response.status_code == 200):

                           

                                # Convert the body of the response to a dict

                                json_data = json.loads(response.text)

                           

                                # Retrieve the authToken from the response.

                                authToken = "authToken " + json_data['response']['authToken']

                           

                                return authToken

                           

                            else:

                                print

                                print 'Authentication Failure - response code: ', response

                                exit()

                           

                            # end of get_authToken() function

                           

                          def create_event(event_data):

                           

                            # Authenticate first.

                            authToken = get_authToken()

                            

                            url = 'https://' + tsim_host + '/bppmws/api/Event/create'

                           

                            headers = {

                                'content-type': "application/json",

                                'Authorization': authToken,

                            }

                           

                            # Payload is the complete event definition in JSON format

                            payload = event_data

                           

                            # Make the call to the API

                            response = requests.post(url, data=payload, headers=headers, verify=False)

                           

                            # Check the return code and capture the response

                            if (response.status_code == 200):

                            json_data = json.loads(response.text)

                            print

                            print 'Successfully created the event.'

                           

                            # print json_data

                           

                            else:

                              print

                              print 'Failed to create the event - response code: ', response

                              exit()

                                

                            return

                           

                          # Main function

                          def main():

                           

                            # Define the TSOM event slots and create a JSON object.

                            json_data = define_event()

                           

                            # Make the call to the API to create the event,

                            create_event(json_data)

                           

                          if __name__ == '__main__':

                              main()

                          3 of 3 people found this helpful
                          • 10. Re: Create an event in TrueSight using a REST call from PowerShell.
                            Vadivel Paramesh

                            Hi Brendan

                            Much appreciated! Thanks a Ton!

                            Let me test this script in my environment and will post the results back here.

                             

                            With kind regards

                            Vels

                            • 11. Re: Create an event in TrueSight using a REST call from PowerShell.
                              Vadivel Paramesh

                              Hi Brendan

                               

                              I have copied the above script and tried it in my environment. When i run the script, i get compilation errors as "IndentationError: expected an indented block" in many places. If you could attach the script here, that would be helpful.

                               

                              With kind regards

                              Vels

                              • 12. Re: Create an event in TrueSight using a REST call from PowerShell.
                                Brendan Murray

                                Hi Vels,

                                 

                                I have attached the script. Let me know if it works for you. Python is very sensitive about how the code is indented.

                                 

                                Regards,

                                 

                                Brendan

                                1 of 1 people found this helpful
                                • 13. Re: Create an event in TrueSight using a REST call from PowerShell.
                                  Vadivel Paramesh

                                  Hi Brendan

                                   

                                  Many Thanks. It worked like a charm!

                                   

                                  With kind regards

                                  Vels

                                  • 14. Re: Create an event in TrueSight using a REST call from PowerShell.
                                    Brendan Murray

                                    Excellent! You are most welcome, Vels.

                                     

                                    Regards,

                                     

                                    Brendan

                                    1 2 Previous Next