Skip to content

Instantly share code, notes, and snippets.

@braoru
Created June 10, 2015 09:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save braoru/977949f0aa54c7702e55 to your computer and use it in GitHub Desktop.
Save braoru/977949f0aa54c7702e55 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2013:
# Sébastien Pasche, sebastien.pasche@leshop.ch
# Mikael Bugnon, mikael.bugnon@leshop.ch
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
author = "Sebastien Pasche"
maintainer = "Sebastien Pasche"
version = "0.0.1"
import optparse
import sys
import traceback
import json
import base64
try:
import winrm
from winrm.protocol import Protocol
except ImportError:
print "ERROR : this plugin needs the local winrm lib. Please install it"
sys.exit(2)
from pprint import pprint
# Ok try to load our directory to load the plugin utils.
# my_dir = os.path.dirname(__file__)
# sys.path.insert(0, my_dir)
DEFAULT_WARNING = '100'
DEFAULT_CRITICAL = '300'
# Powershell
# ----------
ps_script = """
#check input data
#----------------
$CheckInputJSON = '{check_json}' | ConvertFrom-Json
#Obtain data
#Format output
$CheckOuputJson = $CheckInputJSON | ConvertTo-Json
$CheckOuputJsonBytes = [System.Text.Encoding]::UTF8.GetBytes($CheckOuputJson)
$CheckOuputJsonBytesBase64 = [System.Convert]::ToBase64String($CheckOuputJsonBytes)
Write-Host $CheckOuputJsonBytesBase64
"""
# Check
def get_echo(
client,
script
):
responce = client.run_ps(script)
return responce.std_out
# OPT parsing
# -----------
parser = optparse.OptionParser(
"%prog [options]", version="%prog " + version)
parser.add_option('-H', '--hostname',
dest="hostname",
help='Hostname to connect to')
parser.add_option('-p', '--port',
dest="port", type="int", default=5986,
help='WinRM HTTP port to connect to. Default : HTTPS - 5986')
parser.add_option('-s', '--http-scheme',
dest="scheme", default="https",
help='WinRM HTTP scheme to connect to. Default : https://')
parser.add_option('-U', '--user',
dest="user", default="shinken",
help='remote use to use. By default shinken.')
parser.add_option('-P', '--password',
dest="password",
help='Password. By default will use void')
parser.add_option('-w', '--warning',
dest="warning",
help='Warning value for connection. In [ms]. Default : 100 [ms]')
parser.add_option('-c', '--critical',
dest="critical",
help='Critical value for connection. In [ms]. Default : 300 [ms]')
if __name__ == '__main__':
# Ok first job : parse args
opts, args = parser.parse_args()
if args:
parser.error("Does not accept any argument.")
# connection parameters
port = opts.port
hostname = opts.hostname or ''
scheme = opts.scheme
user = opts.user
password = opts.password
# Try to get numeic warning/critical values
s_warning = opts.warning or DEFAULT_WARNING
s_critical = opts.critical or DEFAULT_CRITICAL
try:
# Connect to the remote host
client = winrm.Session(
'{s}://{h}:{p}'.format(
s=scheme,
h=hostname,
p=port
),
auth=(
user,
password
)
)
# Fill script data
data = {
"hello": "world",
"I": "Kick rock das mama"
}
data_string = json.dumps(
data,
sort_keys=True
)
#prepare the script
ps_script = ps_script.format(
check_json=data_string
)
# Execute the powershell script remotly
result = get_echo(
client,
ps_script
)
result = base64.urlsafe_b64decode(result)
result = json.loads(result)
except Exception as e:
the_type, value, tb = sys.exc_info()
pprint(e)
print("Exec Info")
print("type : {t}".format(t=the_type))
print("value : {v}".format(v=value))
print("traceback")
print("---------")
traceback.print_tb(tb)
pprint(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment