简体   繁体   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.

相关问题 如何使用域帐户通过Python(pywinrm)中的WinRM连接到远程计算机? - How to connect to remote machine via WinRM in Python (pywinrm) using domain account? 如何使用python将文件从本地机器上传到浏览器? - How to upload file from local machine to the browser using python? 如何使用python在远程Windows计算机中执行.exe文件 - How to execute .exe file in a remote windows machine using python 如何使用 aws 控制台将带有库的 python 代码从 Windows 本地机器上传到 aws lambda - how to upload python code with libraries to aws lambda from windows local machine using aws console 上传文件到 Windows Sharepoint 使用 Python 3? - Upload File to Windows Sharepoint using Python 3? 如何使用 Python 与 Windows 机器连接 - How to connect with Windows Machine using Python 如何在Windows中的python中处理文件上传? - How to handle file upload in python in windows? 使用python将文件从本地计算机传输到远程Windows服务器 - Transfer file from local machine to remote windows server using python 如何使用cygwin终端在Windows机器上安装python? - How do I install python on a windows machine using a cygwin terminal? 如何使用Python访问其他/远程Windows计算机? - How to access a different/remote Windows machine using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM