def test_winrm_connection(target, port, user, password): protocol = Protocol( endpoint='https://{target}:{port}/wsman'.format(target=target, port=port), transport='ntlm', username=user, password=password, server_cert_validation='ignore') try: shell_id = protocol.open_shell() command_id = protocol.run_command(shell_id, 'whoami') std_out, std_err, status_code = protocol.get_command_output(shell_id, command_id) protocol.cleanup_command(shell_id, command_id) protocol.close_shell(shell_id) return {"msg":"Connection succeed.", "error": "", "output_command": std_out, "status_code": status_code} except Exception: return {"msg":"Connection failed.", "error": sys.exc_info()[1] , "output_command": "", "status_code": ""}
def run_cmd_winrm(cmd: str) -> Response: """ Run batch script using winrm client. Args: cmd: batch script to run. Returns: Response object containing stderr, stdout and exit_status. """ client = Protocol(endpoint='http://{}:5985/wsman'.format(config['host']), transport='ntlm', username='******'.format(config['domain'], config['user']), password=config['pass'], server_cert_validation='ignore') shell_id = client.open_shell() command_id = client.run_command(shell_id, cmd) rs = Response(client.get_command_output(shell_id, command_id)) client.cleanup_command(shell_id, command_id) client.close_shell(shell_id) return rs
#! /usr/bin/python from winrm import Session, Protocol print("Starting PyWinRM Script") host = input("hostname of windows with port: ") user = input("username of windows: ") password = input("password of windows: ") print("Running High Level API Test") s = Session(host, auth=(user, password)) r = s.run_cmd('ipconfig', ['/all']) print(r.std_out, r.std_err) print("Running Low Level API Test") p = Protocol(endpoint='http://' + host + '/wsman', transport='ntlm', username=user, password=password, server_cert_validation='ignore') shell_id = p.open_shell() command_id = p.run_command(shell_id, 'ipconfig', ['/all']) std_out, std_err, status_code = p.get_command_output(shell_id, command_id) p.cleanup_command(shell_id, command_id) p.close_shell(shell_id) print(std_out, std_err, status_code) print("Stopping PyWinRM Script")