forked from Linuxfabrik/lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwinrm.py
83 lines (74 loc) · 2.45 KB
/
winrm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#! /usr/bin/env python2
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst
"""This library collects some Microsoft WinRM related functions.
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2023112901'
try:
import winrm
HAVE_WINRM = True
except ImportError:
HAVE_WINRM = False
from . import txt
def run_ps(args, cmd):
"""Returns a dict.
* result.status_code
* result.std_out
* result.std_err
"""
try:
if args.WINRM_DOMAIN:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=('{}@{}'.format(args.WINRM_USERNAME,
args.WINRM_DOMAIN),
args.WINRM_PASSWORD),
transport=args.WINRM_TRANSPORT,
)
else:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=(args.WINRM_USERNAME, args.WINRM_PASSWORD),
transport=args.WINRM_TRANSPORT,
)
result = session.run_ps(cmd) # run Powershell block
return {
'retc': result.status_code,
'stdout': txt.to_text(result.std_out), # convert from byte to unicode
'stderr': txt.to_text(result.std_err), # convert from byte to unicode
}
except:
return None
def run_cmd(args, cmd, params=[]):
"""Returns a dict.
* result.status_code
* result.std_out
* result.std_err
"""
try:
if args.WINRM_DOMAIN:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=('{}@{}'.format(args.WINRM_USERNAME, args.WINRM_DOMAIN), args.WINRM_PASSWORD),
transport=args.WINRM_TRANSPORT,
)
else:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=(args.WINRM_USERNAME, args.WINRM_PASSWORD),
transport=args.WINRM_TRANSPORT
)
result = session.run_cmd(cmd, params) # run command in cmd.exe
return {
'retc': result.status_code,
'stdout': txt.to_text(result.std_out), # convert from byte to unicode
'stderr': txt.to_text(result.std_err), # convert from byte to unicode
}
except:
return None