def create_connection(protocol, address, port, password, username):
    global conn, shell_id, command_id, stdout, stderr, return_code
    endpoint = "%s://%s:%s/wsman" % (protocol, address, port)
    conn = Protocol(endpoint=endpoint, transport=transport,
                    username=username, password=password)
    shell_id = conn.open_shell()
    return shell_id
Exemple #2
0
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 create_remote_script():
    global conn, shell_id, command_id, stdout, stderr, return_code
    endpoint = "%s://%s:%s/wsman" % (protocol, address, port)
    conn = Protocol(endpoint=endpoint, transport=transport,
                    username=username, password=password)
    shell_id = conn.open_shell()
    # read the content file to var
    with open(file_path, "r") as script_file:
        script_content = script_file.read()
    # the second part of script (this is)_ the script we want create
    text_file = script_content
    # first part of the script to create
    part_1 = """$stream = [System.IO.StreamWriter] "%s%s"
$s = @"
""" % (PS_path, file_name)
    # the last  part of the script
    part_2 = """
"@ | %{ $_.Replace("`n","`r`n") }
$stream.WriteLine($s)
$stream.close()"""
    script = part_1 + text_file + part_2
    encoded_script = base64.b64encode(script.encode("utf_16_le"))
    # send the script to powershell, tell it the script is encoded
    command_id = conn.run_command(shell_id, "powershell -encodedcommand %s" %
                                  (encoded_script))
    stdout, stderr, return_code = conn.get_command_output(shell_id, command_id)
    conn.cleanup_command(shell_id, command_id)
    print "STDOUT: %s" % (stdout)
    print "STDERR: %s" % (stderr)
def get_connection():
    # address = "localhost"
    # transport = "plaintext"
    # username = "******"
    # password = "******"
    # protocol = "http"
    # port = 5985
    # endpoint = "%s://%s:%s/wsman" % (protocol, address, port)

    address = settings.address
    transport = settings.transport
    username = settings.username
    password = settings.password
    protocol = settings.protocol
    port = settings.port
    endpoint = settings.endpoint

    conn = Protocol(endpoint=endpoint, transport=transport,
                    username=username, password=password)
    shell_id = conn.open_shell()

    return conn, shell_id
Exemple #5
0
    def _protocol(self, endpoint: str, transport: str):
        """Create Protocol using low-level API"""

        session = self.session

        protocol = Protocol(endpoint=endpoint,
                            transport=transport,
                            username=self.username,
                            password=self.password,
                            server_cert_validation='ignore',
                            message_encryption='always')

        session.protocol = protocol
        return session
    def winrmadapter_create_session(self, alias, hostname, login, password):
        #Create session with windows host.
        #Does not support domain authentication.
        #*Args:*\n
        #alias_ - robot framework alias to identify the session\n
        #hostname_ -  windows hostname (not IP)\n
        #login_ - windows local login\n
        #password_ - windows local password

        #*Example:*\n
        #| Create Session  |  server  |  windows-host |  Administrator  |  1234567890 |

        session = Protocol(endpoint=hostname,
                           username=login,
                           password=password)

        # This may not be true but use as example
        # Pretend session returns int if successful or null for fail
        if session is uuid:
            return True
        else:
            return False

        print("Performing Create WINRM Session")

        Transaction("WINRMExecutionID",
                    self.currentTest.get_WINRM_executionid(), "INFO",
                    "Performing Create WINRM Session", self.mongo_db)

        #Set Results Value in ResultsData
        self.currentTest.setStepExpectedEvidenceCategory(
            self.active_step_id, "INFO")
        self.currentTest.setStepExpectedResultData(self.active_step_id,
                                                   str(result_value))

        #Set value in global dict
        if results_id in self.results_dict.keys():
            self.results_dict[results_id] = result_value
        else:
            self.results_dict.update({results_id: result_value})

        #Last print should flush the stdout buffer to ensure output is seen correctly not needed once trans logging comes
        print("[" + results_id + "] - Total after operation = " +
              str(result_value),
              flush=True)

        return True
Exemple #7
0
def protocol_fake(request):
    httpretty.reset()
    httpretty.enable()
    httpretty.register_uri(method=httpretty.POST,
                           uri='http://windows-host:5985/wsman',
                           body=transport_stub_callback)

    uuid4_patcher = patch('uuid.uuid4')
    uuid4_mock = uuid4_patcher.start()
    uuid4_mock.return_value = uuid.UUID('11111111-1111-1111-1111-111111111111')

    def teardown():
        httpretty.disable()
        uuid4_patcher.stop()

    request.addfinalizer(teardown)
    return Protocol(endpoint='http://windows-host:5985/wsman')
Exemple #8
0
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
Exemple #9
0
def protocol_real():
    endpoint = os.environ.get('WINRM_ENDPOINT', None)
    transport = os.environ.get('WINRM_TRANSPORT', None)
    username = os.environ.get('WINRM_USERNAME', None)
    password = os.environ.get('WINRM_PASSWORD', None)
    if endpoint:
        # TODO consider replace json with yaml for integration test settings
        # TODO json does not support comments
        settings = {'endpoint': endpoint}
        if transport:
            settings['transport'] = transport
        if username:
            settings['username'] = username
        if password:
            settings['password'] = password

        from winrm.protocol import Protocol
        protocol = Protocol(**settings)
        return protocol
    else:
        skip('WINRM_ENDPOINT environment variable was not set. Integration tests will be skipped')
Exemple #10
0
def setup(configp):
    """
    Setup hvclient globals and create protocol with server host and credentials

    Args:
        configp (dict): Configuration from config file
    """
    global config
    global server
    global vms_cache_filename

    config = configp

    domain = config['domain']
    user = config['user']
    passw = config['pass']
    host = config['host']
    vms_cache_filename = config['cache_file']

    server = Protocol(endpoint='http://{0}:5985/wsman'.format(host),
                      transport='ntlm',
                      username='******'.format(domain, user),
                      password=passw,
                      server_cert_validation='ignore')
#! /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")
class KeywordLibrary:

    # Mandatory Parameters used by Keyword functions to return Test Evidence, Action/Step Data, Access the DB
    currentTest = None
    active_step_id = None
    mongo_db = None
    rm = Protocol()

    def __init__(
        self,
        mongodb=None,
        currentTest=None
    ):  # Executed Per Test Case doTest  should always have CurrentTest
        # This is called on Instance creation which will occur per Test
        self.currentTest = currentTest
        self.mongo_db = mongodb

    def set_step_id(self, step_id):
        #This is required to add Results Data to the active step
        self.active_step_id = step_id

    def populate_regex(adapter_details, mongo_db):
        # Function is skipped when parsing, Executed on Adapter Startup

        #Use Common Function to set the specific regex for fields within the Adapter
        #All other information for the Adapter is gathered directory from the Class Loader
        #This function is ran automatically after parsing of the class

        # Adding a transaction
        Transaction("adapterStartup", "WINRMAdapter", "INFO",
                    "Populate Regex for WINRMAdapter", mongo_db)

        adapter_details.set_regex_for_field("alias", "^[a-zA-Z0-9]*$")
        adapter_details.set_regex_for_field("hostname", "^[a-zA-Z0-9]*$")
        adapter_details.set_regex_for_field("login", "^[a-zA-Z0-9]*$")
        adapter_details.set_regex_for_field(
            "password", "^[a-zA-Z0-9[$&+,:;=?@#|'<>.-^*()%!]]*$")
        adapter_details.set_regex_for_field(
            "command", "^[a-zA-Z0-9[$&+,:;=?@#|'<>.-^*()%!]]*$")
        adapter_details.set_regex_for_field(
            "params", "^[a-zA-Z0-9[$&+,:;=?@#|'<>.-^*()%!]]*$")
        adapter_details.set_regex_for_field(
            "script", "^[a-zA-Z0-9[$&+,:;=?@#|'<>.-^*()%!]]*$")

    def winrmadapter_create_session(self, alias, hostname, login, password):
        #Create session with windows host.
        #Does not support domain authentication.
        #*Args:*\n
        #alias_ - robot framework alias to identify the session\n
        #hostname_ -  windows hostname (not IP)\n
        #login_ - windows local login\n
        #password_ - windows local password

        #*Example:*\n
        #| Create Session  |  server  |  windows-host |  Administrator  |  1234567890 |

        session = Protocol(endpoint=hostname,
                           username=login,
                           password=password)

        # This may not be true but use as example
        # Pretend session returns int if successful or null for fail
        if session is uuid:
            return True
        else:
            return False

        print("Performing Create WINRM Session")

        Transaction("WINRMExecutionID",
                    self.currentTest.get_WINRM_executionid(), "INFO",
                    "Performing Create WINRM Session", self.mongo_db)

        #Set Results Value in ResultsData
        self.currentTest.setStepExpectedEvidenceCategory(
            self.active_step_id, "INFO")
        self.currentTest.setStepExpectedResultData(self.active_step_id,
                                                   str(result_value))

        #Set value in global dict
        if results_id in self.results_dict.keys():
            self.results_dict[results_id] = result_value
        else:
            self.results_dict.update({results_id: result_value})

        #Last print should flush the stdout buffer to ensure output is seen correctly not needed once trans logging comes
        print("[" + results_id + "] - Total after operation = " +
              str(result_value),
              flush=True)

        return True

    def winrmadapter_run_cmd(self, alias, command, params) -> winrm.Response:

        #Execute command on remote machine.

        #*Args:*\n
        #    _alias_ - robot framework alias to identify the session\n
        #    _command_ -  windows command\n
        #    _params_ - lists of command's parameters

        #Returns:*\n
        #    Result object with methods: status_code, std_out, std_err.

        #*Example:*\n
        #| ${params}=  | Create List  |  "/all" |
        #| ${result}=  |  Run cmd  |  server  |  ipconfig  |  ${params} |
        #| Log  |  ${result.status_code} |
        #| Log  |  ${result.std_out} |
        #| Log  |  ${result.std_err} |
        #=>\n
        #| 0
        #| Windows IP Configuration
        #|    Host Name . . . . . . . . . . . . : WINDOWS-HOST
        #|    Primary Dns Suffix  . . . . . . . :
        #|    Node Type . . . . . . . . . . . . : Hybrid
        #|    IP Routing Enabled. . . . . . . . : No
        #|    WINS Proxy Enabled. . . . . . . . : No

        print("Performing WINRM Run Commmand")

        Transaction("WINRMExecutionID",
                    self.currentTest.get_WINRM_executionid(), "INFO",
                    "Performing WINRM Run Commmand", self.mongo_db)

        if params is not None:
            log_cmd = f'{command} {" ".join(params)}'
        else:
            log_cmd = command
        logger.info(f'Run command on server with alias "{alias}": {log_cmd}')
        self._session = self._cache.switch(alias)
        result = self._session.run_cmd(command, params)
        return result

    def winrmadapter_run_ps(self, alias, script) -> winrm.Response:

        #Run power shell script on remote machine.

        #*Args:*\n
        #     _alias_ - robot framework alias to identify the session\n
        #     _script_ -  power shell script\n

        #*Returns:*\n
        #     Result object with methods: status_code, std_out, std_err.

        #*Example:*\n
        #| ${result}=  |  Run ps  |  server  |  get-process iexplore|select -exp ws|measure-object -sum|select -exp Sum |
        #| Log  |  ${result.status_code} |
        #| Log  |  ${result.std_out} |
        #| Log  |  ${result.std_err} |
        # =>\n
        #| 0
        #| 56987648

        logger.info(
            f'Run power shell script on server with alias "{alias}": {script}')
        self._session = self._cache.switch(alias)
        result = self._session.run_ps(script)
        return result
from winrm import Protocol
import base64
import sys
address = "127.0.0.1"
transport = "plaintext"
username = "******"
password = "******"
protocol = "http"
port = 55985

endpoint = "%s://%s:%s/wsman" % (protocol, address, port)

conn = Protocol(endpoint=endpoint, transport=transport,
                username=username, password=password)
shell_id = conn.open_shell()


# the text file we want to send
# this could be populated by reading a file from disk instead
# has some special characters, just to prove they won't be a problem
text_file = """this is a multiline file
that contains special characters such as
"blah"
'#@$*&&($}
that will be written
onto the windows box"""

# first part of the powershell script
# streamwriter is the fastest and most efficient way to write a file
# I have found
# notice the @", this is like a "here document" in linux