import paramiko import os # 使用示例 sftp_host = "172.31.1.3" # SFTP 服务器地址 sftp_port = 22 # SFTP 端口号 sftp_user = 'gpu' # SFTP 登录用户名 sftp_passwd = '2024' # SFTP 登录密码 # 获取当前文件上一层目录,即项目目录 make2 底下 local_root_path = "G:\\obj_fix\print" # 定义函数来递归遍历文件夹下的所有文件 def list_files(directory): for root, dirs, files in os.walk(directory): for file in files: yield os.path.join(root, file) def sftp_upload(sftp_host, sftp_port, sftp_user, sftp_passwd, local_file, remote_file): # 创建 SSH 客户端对象 ssh_client = paramiko.SSHClient() try: # 设置自动添加主机密钥 ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接到 SFTP 服务器 ssh_client.connect(sftp_host, port=sftp_port, username=sftp_user, password=sftp_passwd) # 创建 SFTP 客户端对象 sftp_client = ssh_client.open_sftp() # 判断 local_file 是文件还是目录 if os.path.isdir(local_file): try: # 如果远程目录不存在,则创建 sftp_client.mkdir(remote_file) except IOError: # 目录已存在,忽略 pass # 切换至远程目录 sftp_client.chdir(remote_file) # 遍历本地目录 for file_name in os.listdir(local_file): local_path = os.path.join(local_file, file_name) if os.path.isfile(local_path): # 如果是文件,上传文件 sftp_client.put(local_path, file_name) else: # 如果是文件,直接上传文件 sftp_client.put(local_file, remote_file) print("上传成功") except Exception as e: print(f"上传文件失败:{e}") finally: # 关闭 SFTP 客户端和 SSH 连接 sftp_client.close() ssh_client.close() if __name__ == '__main__': nums = 0 #遍历 local_root_path 下的所有文件 for file_path in list_files(local_root_path): if "around" in file_path: continue if "_old.obj" in file_path: # if ".obj" not in file_path: # continue arrTemp = file_path.split('\\') pid = arrTemp[len(arrTemp)-2] nums += 1 # # pid = "164" # 本地文件路径 dirPath = f'{local_root_path}/{pid}/{pid}.obj' # 远程服务的路径 remote_file = f"/data/datasets/obj_fix/{pid}/{pid}.obj" sftp_upload(sftp_host, sftp_port, sftp_user, sftp_passwd, dirPath, remote_file) print(pid,file_path,"---剩余---",524 - nums)