暂无分类
暂无标签
发布于2021-03-30 22:16 阅读(902) 评论(0) 点赞(29) 收藏(1)
0
1
2
3
4
思路是,使用zipfile对文件进行压缩,之后使用paramiko提供的SFTPClient()上传文件,之后使用paramiko的SSHClient()执行Linux命令操作文件
import os
import zipfile
import paramiko
# 使用zipfile压缩文件
def zip_code(dir_name, zip_name):
file_list = []
if os.path.isfile(dir_name):
file_list.append(dir_name)
else:
for root, dirs, files in os.walk(dir_name):
for name in files:
file_list.append(os.path.join(root, name))
zf = zipfile.ZipFile(zip_name, "w", zipfile.ZIP_DEFLATED)
for tar in file_list:
arc_name = tar[len(dir_name):]
zf.write(tar, arc_name)
zf.close()
# 使用zipfile解压文件(这是直接在本地解压)
# def unzip_file(zip_file_name, unzip_dir):
# zf = zipfile.ZipFile(zip_file_name)
# file_list = zf.namelist()
# for file in file_list:
# zf.extract(file, unzip_dir)
# zf.close()
def upload_code(host, port, username, pwd, local_file, target_path, target_file_name):
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=pwd)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_file, target_path + target_file_name)
client = paramiko.SSHClient()
client._transport = transport
cmd_ls = "ls -l " + target_path + target_file_name
_, stdout, stderr = client.exec_command(cmd_ls)
if not stdout.read().decode('utf-8'):
print("失败: ", stderr.read().decode('utf-8'))
return
# 这里使用unzip解压,但是zipfile压缩的时候对中文不友好,所以unzip解压需要指定CP936编码
cmd = "cd " + target_path + " && sudo rm -rf web_code/* && unzip -O CP936 " + target_file_name + " -d web_code/ && rm " + target_file_name
print("cmd: ", cmd)
_, stdout, stderr = client.exec_command(cmd)
print("stdout:", stdout.read().decode('utf-8'))
print("stderr:", stderr.read().decode('utf-8'))
print("finish")
def start():
username = "root"
pwd = "12345"
host = "localhost"
port = 22
target_file_name = "dist.zip"
local_file = "./{}".format(target_file_name)
target_path = "/test/"
zip_code(r"D:\工作", "./{}".format(target_file_name))
upload_code(host, port, username, pwd, local_file, target_path, target_file_name)
input()
if __name__ == '__main__':
start()
需要注意的是,使用unzip解压的时候即使指定了CP936编码,但还是会有部分中文显示乱码
原文链接:https://blog.csdn.net/qq_39147299/article/details/115309398
0
1
2
3
4
5
6
7
8
9
作者:高富帅
链接: https://www.pythonheidong.com/blog/article/914347/311f784e45ef5c8e1bd7/
来源: python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!