windows远程下载和上传 Python实现

talk is cheap, show my code:

import subprocess
import ctypes

kernel32 = ctypes.windll.kernel32
language_code = {"0x804": "gbk", "0x409": "utf-8"}


def get_default_language_encoding():
    return language_code.get(hex(kernel32.GetSystemDefaultUILanguage()), "utf-8")


class WebClient:
    """
    利用System.Net.WebClient实现下载文件,支持ftp文件下载
    """
    __download_cmd = "$c=new-object System.Net.WebClient;$c.DownloadFile('{url}', '{save_path}')"

    def __init__(self, host=None, user=None, password=None):
        self.host = host
        self.user = user
        self.pwd = password

    def download(self, remote, local):
        if "://" in remote:
            url = remote
        else:
            url = "ftp://{user}:{pwd}@{host}/{file}".format(user=self.user, pwd=self.pwd, host=self.host, file=remote)
        print(remote)
        print(local)
        cmd = '%s' % WebClient.__download_cmd.format(url=url, save_path=local)
        print(cmd)
        p = subprocess.run(['powershell', "-Command", cmd],
                           stdout=-1)
        print(p.stdout.decode("gbk"))


class WindowsRemoteTransport:
    """
    利用Windows自带工具net 和 xcopy实现远程下载和上传
    """

    def __init__(self, host, user, password):
        self.pwd = password
        self.host = host
        self.user = user
        self.connected = False
        self.default_encoding = get_default_language_encoding()

    def connect(self):
        cmd = ['net', 'use', r'\\%s\ipc$' % self.host, '"%s"' % self.pwd, '/user:"%s"' % self.user]
        proc = subprocess.run(cmd, stdout=-1, stderr=-1)
        out = proc.stdout.decode(self.default_encoding)
        err = proc.stderr.decode(self.default_encoding)
        if proc.returncode:
            raise Exception(proc.returncode, err.replace("\r\n", ""))
        print(out)
        self.connected = True

    def __enter__(self):
        self.connect()
        return self

    def x_copy(self, source, destination):
        source = source.replace("/", "\\")
        destination = destination.replace("/", "\\")
        cmd = 'echo f|xcopy "%s" "%s" /c /y /i' % (source, destination)
        proc = subprocess.run(cmd, stderr=-1, stdout=-1, shell=True)
        out = proc.stdout.decode(self.default_encoding)
        if proc.returncode:
            err = proc.stderr.decode(self.default_encoding)
            raise Exception(proc.returncode, err.replace("\r\n", ""))
        print(out)

    def download(self, remote_path, local_path):
        remote_path = r"\\%s\%s" % (self.host, remote_path.replace(":", "$"))
        self.x_copy(remote_path, local_path)

    def upload(self, local_path, remote_path):
        remote_path = r"\\%s\%s" % (self.host, remote_path.replace(":", "$"))
        self.x_copy(local_path, remote_path)

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_tb)
        print("close")
        self.close()

    def close(self):
        cmd = ['net', 'use', r'\\%s\ipc$' % self.host, "/del"]
        proc = subprocess.run(cmd, stdout=-1, stderr=-1)
        out = proc.stdout.decode(self.default_encoding)
        if proc.returncode:
            err = proc.stderr.decode(self.default_encoding)
            raise Exception(proc.returncode, err.replace("\r\n", ""))
        print(out)
        self.connected = False


if __name__ == '__main__':
    with WindowsRemoteTransport("host", "username", "password") as a:
        a.download("remote_path", "local_path")
        a.upload("local_path", "remote_path")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值