12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import paramiko
- import sys
- import os
- def print_progress(transferred, total):
- progress = transferred / total * 100
- sys.stdout.write(f"\r传输进度:{progress:.2f}% ({transferred}/{total} 字节)")
- sys.stdout.flush()
- def sftp_upload(local_path, remote_path, host, port, username, password):
- try:
-
- ssh_client = paramiko.SSHClient()
-
- ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-
- ssh_client.connect(hostname=host, port=port, username=username, password=password)
-
- sftp_client = ssh_client.open_sftp()
-
- try:
- sftp_client.stat(remote_path)
- print(f"远程文件 {remote_path} 已存在")
- except FileNotFoundError:
-
- remote_dir = os.path.dirname(remote_path)
-
- if remote_dir:
- try:
- sftp_client.stat(remote_dir)
- except FileNotFoundError:
- sftp_client.mkdir(remote_dir)
- print(f"已在远程服务器上创建目录 {remote_dir}")
-
- sftp_client.open(remote_path, 'w').close()
- print(f"已在远程服务器上创建文件 {remote_path}")
-
- sftp_client.put(local_path, remote_path, callback=print_progress)
-
- print()
- print(f"文件成功上传")
-
- sftp_client.close()
-
- ssh_client.close()
- except Exception as e:
- print(f"上传文件时发生错误: {e}")
-
- print(f"异常类型: {type(e)}")
-
- print(f"异常消息: {e}")
-
- import traceback
- traceback.print_exc()
- if __name__ == "__main__":
-
- if len(sys.argv) < 7:
- print("用法: python script.py <本地文件路径> <远程文件路径> <SFTP服务器地址> <端口> <用户名> <密码>")
- sys.exit(1)
- local_path = sys.argv[1]
- remote_path = sys.argv[2]
- host = sys.argv[3]
- port = int(sys.argv[4])
- username = sys.argv[5]
- password = sys.argv[6]
-
- if not os.path.exists(local_path):
- print(f"本地文件 {local_path} 不存在")
- sys.exit(1)
-
- sftp_upload(local_path, remote_path, host, port, username, password)
|