使用Python代码创建工单

该页面包含各种语言的示例脚本,这些脚本可通过命令行在iTop中创建工单。脚本使用iTop的RESTTJSON API在远程iTop服务器上创建工单(脚本必须可以通过httpphttps访问iTop)。该脚本旨在与Nagios一起使用,因为它们需要4个参数: host, service, service_status和service_state_type,但是唯一有意义的参数是主机,并且可以很容易地将脚本调整为特定的服务。

用您的常用脚本语言选择脚本,不要犹豫来定制它。

使用PHP

本节提供了一个示例脚本的PHP 脚本语言,以使用RESTTJSON Web服务在(远程)iTop中创建工单。为了简化本示例,仅执行最少的参数验证和返回状况。

求:PHP与cURL模块。

制:Nagios中的“主机”价值必须与iTop中唯一的FunctionalCI的名称相对应。

create-ticket.php
 

#!/usr/bin/php <?php // Configuration $ITOP_URL = 'https://demo.combodo.com/simple'; $ITOP_USER = 'admin'; $ITOP_PWD = 'admin'; $TICKET_CLASS = 'UserRequest'; $TITLE = 'Service Down on %1$s'; $DESCRIPTION = 'The Service "%2$s" is down on "%1$s"'; $COMMENT = 'Created from PHP'; if ($argc != 5) { echo "Usage: {$argv[0]} <host> <service> <service_status> <service_state_type>\n"; ; } $host = $argv[1]; $service = $argv[2]; $service_status = $argv[3]; $service_state_type = $argv[4]; $url = $ITOP_URL.'/webservices/rest.php?version=1.0'; if (($service_status != "OK") && ($service_status != "UP") && ($service_state_type == "HARD")) { $payload = ( 'operation' => 'core/create', 'class' => $TICKET_CLASS, 'fields' => ( 'org_id' => ('SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id = O.id WHERE CI.name="%1$s"', $host), 'title' => ($TITLE, $host, $service), 'description' => ($DESCRIPTION, $host, $service), 'functionalcis_list' => ( ('functionalci_id' => ("SELECT FunctionalCI WHERE name='%s'", $host), 'impact_code' => 'manual'), ), ), 'comment' => $COMMENT, 'output_fields' => 'id', ); $data = ( 'auth_user' => $ITOP_USER, 'auth_pwd' => $ITOP_PWD, 'json_data' => ($payload) ); $options = ( CURLOPT_POST => ($data), CURLOPT_POSTFIELDS => ($data), // Various options... CURLOPT_RETURNTRANSFER => true, // return the content of the request CURLOPT_HEADER => false, // don't return the headers in the output CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect CURLOPT_TIMEOUT => 120, // timeout on response // Disabling SSL verification CURLOPT_SSL_VERIFYPEER => false, // Disable SSL certificate validation CURLOPT_SSL_VERIFYHOST => false, // Disable host vs certificate validation ); $handle = ($url); ($handle, $options); $response = ($handle); $errno = ($handle); $error_message = ($handle); ($handle); if ($errno !== 0) { echo "Problem opening URL: $url, $error_message\n"; ; } $decoded_response = ($response, true); if ($decoded_response === false) { echo "Error: ".($response, true)."\n"; } else if ($decoded_response['code'] != 0) { echo $decoded_response['message']."\n"; } else { echo "Ticket created.\n"; } } else { echo "Service state type !='HARD', doing nothing.\n"; }

用法

create-ticket.php <host> <service> <service_status> <service_state_type>

配置

提供的用户账号必须具有足够的权利才能创建工单并将配置项附加到其上。如有疑问,请与管理员账号一起使用测试。

// Configuration
$ITOP_URL = 'https://demo.combodo.com/simple';
$ITOP_USER = 'admin';
$ITOP_PWD = 'admin';
$TICKET_CLASS = 'UserRequest';
$TITLE = 'Service Down on %1$s';
$DESCRIPTION = 'The Service "%2$s" is down on "%1$s"';
$COMMENT = 'Created from PHP'

提供的用户帐户必须具有足够的权限才能创建票证并将CI附加到票证。如有疑问,请使用管理员帐户进行测试。

故障排除

您可以通过手动运行脚本来测试工单创建。例如,如果iTop中存在一个名为Server1的服务器,则可以运行以下命令来创建工单:

create-ticket.php "Server1" "Manual Test" "DOWN" "HARD"

使用Perl

本节提供了一个示例脚本perl 脚本语言,以使用RESTTJSON Web服务在(远程)iTop中创建工单。为了简化本示例,仅执行最少的参数验证和返回状况。

求:具有LWP和JSON模块的Perl。

制:Nagios中的“主机”价值必须与iTop中唯一的FunctionalCI的名称相对应。

下列perl 脚本会创建一个UserRequest工单(您可以变更,配置来创建事件或变更),并将附带的主机(= FunctionalCI)附加到该脚本。工单与主机在同一组织中创建。

create-ticket.pl
 

#!/usr/bin/perl use strict; use warnings; use LWP 5.64; use JSON; # Default values my $ITOP_URL = 'https://demo.combodo.com/simple'; my $ITOP_LOGIN = "admin"; my $ITOP_PWD = "admin"; my $TICKET_CLASS = 'UserRequest'; my $DEFAULT_DESCRIPTION = 'Service "%1$s" is down on host "%2$s"'; my $DEFAULT_TITLE = 'Service down on "%1$s"'; my $COMMENT = "Created from $0"; # Parameters checking my ($host, $service, $service_status, $service_state_type) = @ARGV; if (not $host) { "Parameter 1: 'host' needed.\n"; } if (not $service) { "Parameter 2: 'service' needed.\n"; } if (not $service_status) { "Parameter 3: 'service status' needed.\n"; } if (not $service_state_type) { "Parameter 4: 'service state type' needed.\n"; } if ( ($service_status ne "OK" ) && ( $service_status ne "UP" ) && ( $service_state_type eq "HARD" )) { my $url = "$ITOP_URL/webservices/rest.php?version=1.0"; my $browser = LWP::UserAgent->new; $browser->ssl_opts(verify_hostname => 0, SSL_verify_mode => 0x00); my %ci_link = ( 'functionalci_id' => "SELECT FunctionalCI WHERE name='$host'", 'impact_code' => 'manual'); my %fields = ( 'org_id' => "SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id=O.id WHERE CI.name='$host'", 'title' => ($DEFAULT_TITLE, $host), 'description' => ($DEFAULT_DESCRIPTION, $service, $host), 'functionalcis_list' => [ \%ci_link ], ); my %data = ( 'operation' => 'core/create', 'class' => $TICKET_CLASS, 'comment' => $COMMENT, 'output_fields' => 'id', 'fields' => \%fields, ); my $response = $browser->post($url, [ 'auth_user' => $ITOP_LOGIN, 'auth_pwd' => $ITOP_PWD, 'json_data' => encode_json \%data, ]); if ($response->is_success) { my $output = decode_json( $response->decoded_content); # or whatever if ($output->{'code'} != 0) { $output->{'message'}."\n"; } else { "Ticket created.\n"; } } else { $response->status_line; } } else { "Service state type !='HARD', doing nothing.\n"; }

用法

create-ticket.pl <host> <service> <service_status> <service_state_type>

配置

编辑以下几行(在脚本的开头)以将脚本调整为适用于您的环境:

# Default values
my $ITOP_URL = 'https://demo.combodo.com/simple';
my $ITOP_LOGIN = "admin";
my $ITOP_PWD = "admin";
my $TICKET_CLASS = 'UserRequest';
my $DEFAULT_DESCRIPTION = 'Service "%1$s" is down on host "%2$s"';
my $DEFAULT_TITLE = 'Service down on "%1$s"';
my $COMMENT = "Created from $0";

提供的用户账号必须具有足够的权利才能创建工单并将配置项附加到其上。如有疑问,请与管理员账号一起使用测试。

故障排除

您可以通过手动运行脚本来测试工单创建。例如,如果iTop中存在一个名为Server1的服务器,则可以运行以下命令来创建工单:

create-ticket.pl "Server1" "Manual Test" "DOWN" "HARD"

使用Python

本节提供了一个示例脚本python 脚本语言,以使用REST/JSON Web服务在(远程)iTop中创建工单。为了简化本示例,仅执行最少的参数验证和返回状况。

求:带有请求,json和(显然)sys程序包的python。

制:Nagios中的“主机”价值必须与iTop中唯一的FunctionalCI的名称相对应。

下列python 脚本会创建一个UserRequest工单(您可以变更,配置来创建事件或变更),并将附带的主机(= FunctionalCI)附加到该脚本。工单与主机在同一组织中创建。

create-ticket.py
 
#!/usr/bin/python
import requests
import json
import sys
 
ITOP_URL = 'https://demo.combodo.com/simple'
ITOP_USER = 'admin'
ITOP_PWD = 'admin'
TICKET_CLASS = 'UserRequest'
TITLE = 'Service down on %(host)s'
DESCRIPTION = 'The service %(service)s is down on %(host)s'
COMMENT = 'Created from Python'
 
if len(sys.argv) != 5:
        print "Usage: "+sys.argv[0]+" host service service_status service_state_type\n"
        sys.exit()
else:
        print str(sys.argv)
        host = sys.argv[1]
        service = sys.argv[2]
        service_status = sys.argv[3]
        service_state_type = sys.argv[4]
 
if (service_status != "OK") and (service_status != "UP") and (service_state_type == "HARD" ):
        json_data = {
                'operation': 'core/create',
                'class': TICKET_CLASS,
                'fields': {
                        'title': TITLE % {'host': host },
                        'description': DESCRIPTION % {'host': host, 'service': service },
                        'org_id': 'SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id = O.id WHERE CI.name="%(host)s"' % {'host': host},
                        'functionalcis_list': [ {
                                'functionalci_id': "SELECT FunctionalCI WHERE name='%(host)s'" % {'host': host},
                                'impact_code': 'manual',
                        }],
                },
                'comment': COMMENT,
                'output_fields': 'id',
        }
        encoded_data = json.dumps(json_data)
        r = requests.post(ITOP_URL+'/webservices/rest.php?version=1.0', verify=False, data={'auth_user': ITOP_USER , 'auth_pwd': ITOP_PWD , 'json_data': encoded_data})
        result = json.loads(r.text);
        if result['code'] == 0:
                print "Ticket created.\n"
        else:
                print result['message']+"\n"
else:
        print "Service state type !='HARD', doing nothing.\n"

用法

create-ticket.py <host> <service> <service_status> <service_state_type>

配置

编辑以下几行(在脚本的开头)以将脚本调整为适用于您的环境:

ITOP_URL = 'https://demo.combodo.com/simple'
ITOP_USER = 'admin'
ITOP_PWD = 'admin'
TICKET_CLASS = 'UserRequest'
TITLE = 'Service down on %(host)s'
DESCRIPTION = 'The service %(service)s is down on %(host)s'
COMMENT = 'Created from Python'

提供的用户账号必须具有足够的权利才能创建工单并将配置项附加到其上。如有疑问,请与管理员账号一起使用测试。

故障排除

您可以通过手动运行脚本来测试工单创建。例如,如果iTop中存在一个名为Server1的服务器,则可以运行以下命令来创建工单:

create-ticket.py "Server1" "Manual Test" "DOWN" "HARD"

使用bash和wget

本节提供了一个示例脚本bash 脚本语言,以使用REST/JSON Web服务在(远程)iTop中创建工单。为了简化本示例,仅执行最少的参数验证和返回状况。

要求:bash和wget。

制:Nagios中的“主机”价值必须与iTop中唯一的FunctionalCI的名称相对应。

下列bash 脚本创建一个UserRequest工单(您可以变更,配置来创建事件或变更),并将附带的配置项附加到该脚本。工单与配置项在同一组织中创建。

create-ticket.bash
 
#!/bin/bash
##################################################################################
#                                                                                #
# Example script for creating a UserRequest ticket via the REST/JSON webservices #
#                                                                                #
##################################################################################
 
# iTop location and credentials, change them to suit your iTop installation
ITOP_URL="https://demo.combodo.com/simple"
ITOP_USER="admin"
ITOP_PWD="admin"
 
 
# Parameters checking, see below for default values
if [ "$1" == "" ]; then
        echo "Missing parameter 1: host"
        exit -1
else
        HOST="$1"
fi
 
if [ "$2" == "" ]; then
        echo "Missing parameter 2: Service"
        exit -1
else
        SERVICE="$2"
fi
 
if [ "$3" == "" ]; then
        echo "Missing parameter 3: Service Status"
        exit -1
else
        SERVICE_STATUS="$3"
fi
 
if [ "$4" == "" ]; then
        echo "Missing parameter 4: Service State Type"
        exit -1
else
        SERVICE_STATUS_TYPE="$4"
fi
 
# Default values, adapt them to your configuration
TICKET_CLASS="UserRequest"
ORGANIZATION="SELECT Organization JOIN FunctionalCI AS CI ON CI.org_id=Organization.id WHERE CI.name='"${HOST}"'"
TITLE="Service Down on $1"
DESCRIPTION="The service $SERVICE is in state $SERVICE_STATUS on $HOST"
 
# Let's create the ticket via the REST/JSON API
if [[ ( "$SERVICE_STATUS" != "OK" ) && ( "$SERVICE_STATUS" != "UP" ) && ( "$SERVICE_STATUS_TYPE" == "HARD" ) ]]; then
        CIS_LIST='[{"functionalci_id":"SELECT FunctionalCI WHERE  name=\"'"$1"'\"", "impact_code": "manual"}]'
        JSON_DATA='{"operation":"core/create", "class":"'"${TICKET_CLASS}"'", "fields": {"functionalcis_list":'"${CIS_LIST}"', "org_id":"'"${ORGANIZATION}"'", "title":"'"$TITLE"'", "description":"'"$DESCRIPTION"'"}, "comment": "Created by the Monitoring", "output_fields": "id"}'
 
        RESULT=`wget -q --post-data='auth_user='"${ITOP_USER}"'&auth_pwd='"${ITOP_PWD}"'&json_data='"${JSON_DATA}" --no-check-certificate -O -  "${ITOP_URL}/webservices/rest.php?version=1.0"`
 
        PATTERN='"key":"([0-9])+"'
        if [[ $RESULT =~ $PATTERN ]]; then
                echo "Ticket created successfully"
        else
                echo "ERROR: failed to create ticket"
                echo $RESULT
        fi
else
        echo "Service State Type != HARD, doing nothing"
fi

用法

create-ticket.bash <host> <service> <service_status> <service_state_type>

配置

变更脚本顶部的3行调整为您的环境

ITOP_URL="https://demo.combodo.com/simple"
ITOP_USER="admin"
ITOP_PWD="admin"

提供的用户账号必须具有足够的权利才能创建工单并将配置项附加到其上。如有疑问,请与管理员账号一起使用测试。

然后根据您的喜好变更的默认值:

# Default values, adapt them to your configuration
TICKET_CLASS="UserRequest"
ORGANIZATION="SELECT Organization JOIN FunctionalCI AS CI ON CI.org_id=Organization.id WHERE CI.name='"${HOST}"'"
TITLE="Service Down on $1"
DESCRIPTION="The service $SERVICE is in state $SERVICE_STATUS on $HOST"

故障排除

您可以通过手动运行脚本来测试工单创建。例如,如果iTop中存在一个名为Server1的服务器,则可以运行以下命令来创建工单:

create-ticket.bash "Server1" "Manual Test" "DOWN" "HARD"

原创链接:https://www.itophub.io/wiki/page?id=2_7_0%3Aadvancedtopics%3Acreate_ticket#using_python


Scripts for creating a ticket from the command line

This page contains example scripts, in various languages, to create a ticket in iTop from the command line. The scripts use the REST/JSON API of iTop to create a ticket on a remote iTop server (the script must have access to iTop through http/https). The scripts are intended for use with Nagios, since they expect 4 parameters: host, service, service_status and service_state_type, but the only meaningful parameter is the host and it is quite easy to adjust the scripts to your specific needs.

Pick the script in your favorite scripting language and don't hesitate to tailor it.

Using PHP

This section provides an example script in the PHP scripting language to create a ticket in a (remote) iTop using the REST/JSON webservices. For the simplicity of this example, only a minimal validation of the parameters and return status is performed.

Requirements: PHP with the cURL module.

Limitation: the “host” value in Nagios must correspond to the name of a unique FunctionalCI in iTop.

The following PHP script creates a UserRequest ticket (you can change the configuration to create either an Incident or a Change) and attaches the supplied host (= FunctionalCI) to it. The ticket is created in the same Organization as the host.

create-ticket.php
 

#!/usr/bin/php <?php // Configuration $ITOP_URL = 'https://demo.combodo.com/simple'; $ITOP_USER = 'admin'; $ITOP_PWD = 'admin'; $TICKET_CLASS = 'UserRequest'; $TITLE = 'Service Down on %1$s'; $DESCRIPTION = 'The Service "%2$s" is down on "%1$s"'; $COMMENT = 'Created from PHP'; if ($argc != 5) { echo "Usage: {$argv[0]} <host> <service> <service_status> <service_state_type>\n"; ; } $host = $argv[1]; $service = $argv[2]; $service_status = $argv[3]; $service_state_type = $argv[4]; $url = $ITOP_URL.'/webservices/rest.php?version=1.0'; if (($service_status != "OK") && ($service_status != "UP") && ($service_state_type == "HARD")) { $payload = ( 'operation' => 'core/create', 'class' => $TICKET_CLASS, 'fields' => ( 'org_id' => ('SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id = O.id WHERE CI.name="%1$s"', $host), 'title' => ($TITLE, $host, $service), 'description' => ($DESCRIPTION, $host, $service), 'functionalcis_list' => ( ('functionalci_id' => ("SELECT FunctionalCI WHERE name='%s'", $host), 'impact_code' => 'manual'), ), ), 'comment' => $COMMENT, 'output_fields' => 'id', ); $data = ( 'auth_user' => $ITOP_USER, 'auth_pwd' => $ITOP_PWD, 'json_data' => ($payload) ); $options = ( CURLOPT_POST => ($data), CURLOPT_POSTFIELDS => ($data), // Various options... CURLOPT_RETURNTRANSFER => true, // return the content of the request CURLOPT_HEADER => false, // don't return the headers in the output CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect CURLOPT_TIMEOUT => 120, // timeout on response // Disabling SSL verification CURLOPT_SSL_VERIFYPEER => false, // Disable SSL certificate validation CURLOPT_SSL_VERIFYHOST => false, // Disable host vs certificate validation ); $handle = ($url); ($handle, $options); $response = ($handle); $errno = ($handle); $error_message = ($handle); ($handle); if ($errno !== 0) { echo "Problem opening URL: $url, $error_message\n"; ; } $decoded_response = ($response, true); if ($decoded_response === false) { echo "Error: ".($response, true)."\n"; } else if ($decoded_response['code'] != 0) { echo $decoded_response['message']."\n"; } else { echo "Ticket created.\n"; } } else { echo "Service state type !='HARD', doing nothing.\n"; }

Usage

create-ticket.php <host> <service> <service_status> <service_state_type>

Configuration

Edit the following lines (at the beginning of the script) to adjust the script to your environment:

// Configuration
$ITOP_URL = 'https://demo.combodo.com/simple';
$ITOP_USER = 'admin';
$ITOP_PWD = 'admin';
$TICKET_CLASS = 'UserRequest';
$TITLE = 'Service Down on %1$s';
$DESCRIPTION = 'The Service "%2$s" is down on "%1$s"';
$COMMENT = 'Created from PHP'

The supplied user account must have enough rights to create the ticket and attach the CI to it. In case of doubt, test with an admin account.

Troubleshooting

You can test the ticket creation by running the script manually. For example, if a server called Server1 exists in your iTop, you can run the following command to create a ticket:

create-ticket.php "Server1" "Manual Test" "DOWN" "HARD"

Using Perl

This section provides an example script in the Perl scripting language to create a ticket in a (remote) iTop using the REST/JSON webservices. For the simplicity of this example, only a minimal validation of the parameters and return status is performed.

Requirements: Perl with the LWP and JSON modules.

Limitation: the “host” value in Nagios must correspond to the name of a unique FunctionalCI in iTop.

The following Perl script creates a UserRequest ticket (you can change the configuration to create either an Incident or a Change) and attaches the supplied host (= FunctionalCI) to it. The ticket is created in the same Organization as the host.

create-ticket.pl
 

#!/usr/bin/perl use strict; use warnings; use LWP 5.64; use JSON; # Default values my $ITOP_URL = 'https://demo.combodo.com/simple'; my $ITOP_LOGIN = "admin"; my $ITOP_PWD = "admin"; my $TICKET_CLASS = 'UserRequest'; my $DEFAULT_DESCRIPTION = 'Service "%1$s" is down on host "%2$s"'; my $DEFAULT_TITLE = 'Service down on "%1$s"'; my $COMMENT = "Created from $0"; # Parameters checking my ($host, $service, $service_status, $service_state_type) = @ARGV; if (not $host) { "Parameter 1: 'host' needed.\n"; } if (not $service) { "Parameter 2: 'service' needed.\n"; } if (not $service_status) { "Parameter 3: 'service status' needed.\n"; } if (not $service_state_type) { "Parameter 4: 'service state type' needed.\n"; } if ( ($service_status ne "OK" ) && ( $service_status ne "UP" ) && ( $service_state_type eq "HARD" )) { my $url = "$ITOP_URL/webservices/rest.php?version=1.0"; my $browser = LWP::UserAgent->new; $browser->ssl_opts(verify_hostname => 0, SSL_verify_mode => 0x00); my %ci_link = ( 'functionalci_id' => "SELECT FunctionalCI WHERE name='$host'", 'impact_code' => 'manual'); my %fields = ( 'org_id' => "SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id=O.id WHERE CI.name='$host'", 'title' => ($DEFAULT_TITLE, $host), 'description' => ($DEFAULT_DESCRIPTION, $service, $host), 'functionalcis_list' => [ \%ci_link ], ); my %data = ( 'operation' => 'core/create', 'class' => $TICKET_CLASS, 'comment' => $COMMENT, 'output_fields' => 'id', 'fields' => \%fields, ); my $response = $browser->post($url, [ 'auth_user' => $ITOP_LOGIN, 'auth_pwd' => $ITOP_PWD, 'json_data' => encode_json \%data, ]); if ($response->is_success) { my $output = decode_json( $response->decoded_content); # or whatever if ($output->{'code'} != 0) { $output->{'message'}."\n"; } else { "Ticket created.\n"; } } else { $response->status_line; } } else { "Service state type !='HARD', doing nothing.\n"; }

Usage

create-ticket.pl <host> <service> <service_status> <service_state_type>

Configuration

Edit the following lines (at the beginning of the script) to adjust the script to your environment:

# Default values
my $ITOP_URL = 'https://demo.combodo.com/simple';
my $ITOP_LOGIN = "admin";
my $ITOP_PWD = "admin";
my $TICKET_CLASS = 'UserRequest';
my $DEFAULT_DESCRIPTION = 'Service "%1$s" is down on host "%2$s"';
my $DEFAULT_TITLE = 'Service down on "%1$s"';
my $COMMENT = "Created from $0";

The supplied user account must have enough rights to create the ticket and attach the CI to it. In case of doubt, test with an admin account.

Troubleshooting

You can test the ticket creation by running the script manually. For example, if a server called Server1 exists in your iTop, you can run the following command to create a ticket:

create-ticket.pl "Server1" "Manual Test" "DOWN" "HARD"

Using Python

This section provides an example script in the python scripting language to create a ticket in a (remote) iTop using the REST/JSON webservices. For the simplicity of this example, only a minimal validation of the parameters and return status is performed.

Requirements: python with the requests, json and (obviously) sys packages.

Limitation: the “host” value in Nagios must correspond to the name of a unique FunctionalCI in iTop.

The following python script creates a UserRequest ticket (you can change the configuration to create either an Incident or a Change) and attaches the supplied host (= FunctionalCI) to it. The ticket is created in the same Organization as the host.

create-ticket.py
 
#!/usr/bin/python
import requests
import json
import sys
 
ITOP_URL = 'https://demo.combodo.com/simple'
ITOP_USER = 'admin'
ITOP_PWD = 'admin'
TICKET_CLASS = 'UserRequest'
TITLE = 'Service down on %(host)s'
DESCRIPTION = 'The service %(service)s is down on %(host)s'
COMMENT = 'Created from Python'
 
if len(sys.argv) != 5:
        print "Usage: "+sys.argv[0]+" host service service_status service_state_type\n"
        sys.exit()
else:
        print str(sys.argv)
        host = sys.argv[1]
        service = sys.argv[2]
        service_status = sys.argv[3]
        service_state_type = sys.argv[4]
 
if (service_status != "OK") and (service_status != "UP") and (service_state_type == "HARD" ):
        json_data = {
                'operation': 'core/create',
                'class': TICKET_CLASS,
                'fields': {
                        'title': TITLE % {'host': host },
                        'description': DESCRIPTION % {'host': host, 'service': service },
                        'org_id': 'SELECT Organization AS O JOIN FunctionalCI AS CI ON CI.org_id = O.id WHERE CI.name="%(host)s"' % {'host': host},
                        'functionalcis_list': [ {
                                'functionalci_id': "SELECT FunctionalCI WHERE name='%(host)s'" % {'host': host},
                                'impact_code': 'manual',
                        }],
                },
                'comment': COMMENT,
                'output_fields': 'id',
        }
        encoded_data = json.dumps(json_data)
        r = requests.post(ITOP_URL+'/webservices/rest.php?version=1.0', verify=False, data={'auth_user': ITOP_USER , 'auth_pwd': ITOP_PWD , 'json_data': encoded_data})
        result = json.loads(r.text);
        if result['code'] == 0:
                print "Ticket created.\n"
        else:
                print result['message']+"\n"
else:
        print "Service state type !='HARD', doing nothing.\n"

Usage

create-ticket.py <host> <service> <service_status> <service_state_type>

Configuration

Edit the following lines (at the beginning of the script) to adjust the script to your environment:

ITOP_URL = 'https://demo.combodo.com/simple'
ITOP_USER = 'admin'
ITOP_PWD = 'admin'
TICKET_CLASS = 'UserRequest'
TITLE = 'Service down on %(host)s'
DESCRIPTION = 'The service %(service)s is down on %(host)s'
COMMENT = 'Created from Python'

The supplied user account must have enough rights to create the ticket and attach the CI to it. In case of doubt, test with an admin account.

Troubleshooting

You can test the ticket creation by running the script manually. For example, if a server called Server1 exists in your iTop, you can run the following command to create a ticket:

create-ticket.py "Server1" "Manual Test" "DOWN" "HARD"

Using bash and wget

This section provides an example script in the bash scripting language to create a ticket in a (remote) iTop using the REST/JSON webservices. For the simplicity of this example, only a minimal validation of the parameters and return status is performed.

Requirements: bash and wget.

Limitation: the “host” value in Nagios must correspond to the name of a unique FunctionalCI in iTop.

The following bash script creates a UserRequest ticket (you can change the configuration to create either an Incident or a Change) and attaches the supplied CI to it. The ticket is created in the same Organization as the CI.

create-ticket.bash
 
#!/bin/bash
##################################################################################
#                                                                                #
# Example script for creating a UserRequest ticket via the REST/JSON webservices #
#                                                                                #
##################################################################################
 
# iTop location and credentials, change them to suit your iTop installation
ITOP_URL="https://demo.combodo.com/simple"
ITOP_USER="admin"
ITOP_PWD="admin"
 
 
# Parameters checking, see below for default values
if [ "$1" == "" ]; then
        echo "Missing parameter 1: host"
        exit -1
else
        HOST="$1"
fi
 
if [ "$2" == "" ]; then
        echo "Missing parameter 2: Service"
        exit -1
else
        SERVICE="$2"
fi
 
if [ "$3" == "" ]; then
        echo "Missing parameter 3: Service Status"
        exit -1
else
        SERVICE_STATUS="$3"
fi
 
if [ "$4" == "" ]; then
        echo "Missing parameter 4: Service State Type"
        exit -1
else
        SERVICE_STATUS_TYPE="$4"
fi
 
# Default values, adapt them to your configuration
TICKET_CLASS="UserRequest"
ORGANIZATION="SELECT Organization JOIN FunctionalCI AS CI ON CI.org_id=Organization.id WHERE CI.name='"${HOST}"'"
TITLE="Service Down on $1"
DESCRIPTION="The service $SERVICE is in state $SERVICE_STATUS on $HOST"
 
# Let's create the ticket via the REST/JSON API
if [[ ( "$SERVICE_STATUS" != "OK" ) && ( "$SERVICE_STATUS" != "UP" ) && ( "$SERVICE_STATUS_TYPE" == "HARD" ) ]]; then
        CIS_LIST='[{"functionalci_id":"SELECT FunctionalCI WHERE  name=\"'"$1"'\"", "impact_code": "manual"}]'
        JSON_DATA='{"operation":"core/create", "class":"'"${TICKET_CLASS}"'", "fields": {"functionalcis_list":'"${CIS_LIST}"', "org_id":"'"${ORGANIZATION}"'", "title":"'"$TITLE"'", "description":"'"$DESCRIPTION"'"}, "comment": "Created by the Monitoring", "output_fields": "id"}'
 
        RESULT=`wget -q --post-data='auth_user='"${ITOP_USER}"'&auth_pwd='"${ITOP_PWD}"'&json_data='"${JSON_DATA}" --no-check-certificate -O -  "${ITOP_URL}/webservices/rest.php?version=1.0"`
 
        PATTERN='"key":"([0-9])+"'
        if [[ $RESULT =~ $PATTERN ]]; then
                echo "Ticket created successfully"
        else
                echo "ERROR: failed to create ticket"
                echo $RESULT
        fi
else
        echo "Service State Type != HARD, doing nothing"
fi

Usage

create-ticket.bash <host> <service> <service_status> <service_state_type>

Configuration

Change the 3 lines at the top of the script to adjust to your environment

ITOP_URL="https://demo.combodo.com/simple"
ITOP_USER="admin"
ITOP_PWD="admin"

The supplied user account must have enough rights to create the ticket and attach the CI to it. In case of doubt, test with an admin account.

Then change the default values to your taste:

# Default values, adapt them to your configuration
TICKET_CLASS="UserRequest"
ORGANIZATION="SELECT Organization JOIN FunctionalCI AS CI ON CI.org_id=Organization.id WHERE CI.name='"${HOST}"'"
TITLE="Service Down on $1"
DESCRIPTION="The service $SERVICE is in state $SERVICE_STATUS on $HOST"

Troubleshooting

You can test the ticket creation by running the script manually. For example, if a server called Server1 exists in your iTop, you can run the following command to create a ticket:

create-ticket.bash "Server1" "Manual Test" "DOWN" "HARD"
标签:
由 superadmin 在 2020/08/27, 16:22 创建
    

需要帮助?

如果您需要有关XWiki的帮助,可以联系:

深圳市艾拓先锋企业管理咨询有限公司