如何使用winrm+将文件上载到windows计算机;python

如何使用winrm+将文件上载到windows计算机;python,python,winrm,Python,Winrm,那么,如何使用WinRM+Python将文件上载到windows计算机 import base64 class WinRMUtil: def __init__(self, session): self.session = session def upload_file(local_filename, remote_filename): file = open(local_filename, 'rt') text = file.r

那么,如何使用WinRM+Python将文件上载到windows计算机

import base64

class WinRMUtil:
    def __init__(self, session):
        self.session = session

    def upload_file(local_filename, remote_filename):
        file = open(local_filename, 'rt')
        text = file.read()
        text = text.replace('\n', '\r\n')
        file.close()
        self._create_remote_file(remote_filename, text)

    def _create_remote_file(self, remote_filename, text):
        step = 400
        utf8 = text.encode("utf8")
        for i in range(0, len(utf8), step):
            self._do_put_file(remote_filename, utf8[i:i + step])

    def _do_put_file(self, location, contents):
        # adapted/copied from https://github.com/diyan/pywinrm/issues/18
        p1 = """
$filePath = "{}"
$s = @"
{}
"@""" % (location, base64.b64encode(contents).decode('utf8'))

        p2 = """
$data = [System.Convert]::FromBase64String($s)
add-content -value $data -encoding byte -path $filePath
"""
        ps_script = p1 + p2
        encoded_ps = base64.b64encode(ps_script.encode('utf_16_le')).decode('utf8')
        rs = self.session.run_cmd('powershell -encodedcommand {0}'.format(encoded_ps))
        if rs.status_code == 1:
            self._log.warning(rs.std_err)
            return None
        return rs.std_out