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")