簡體   English   中英

如何使用Winrm + Python將文件上傳到Windows計算機

[英]How to upload a file to windows machine using winrm+Python

那么,如何使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM