关于把文件从Windows服务器文件传输到Linux服务器的细节

这里采用SFTP协议

 

def upload_sftp(ipaddress, port, uname, passwd, source_path, target_path, filename_include):
    import paramiko
    import os

    try:
        transport = paramiko.Transport((ipaddress, port))
        transport.connect(username=uname, password=passwd)
        sftp = paramiko.SFTPClient.from_transport(transport)
        print(f"Connected to {ipaddress} successfully.")
    except Exception as e:
        print(f"Failed to connect to SFTP server: {e}")
        return

    try:
        for file_name in os.listdir(source_path):
            if filename_include in file_name:
                # 使用os.path.join确保本地路径分隔符正确
                local_file_path = os.path.join(source_path, file_name)
                # 构建远程文件路径,注意这里不需要使用os.path.join,因为远程路径是手动指定的
                remote_file_path = target_path.rstrip("/") + "/" + file_name  # ??理解这一行的作用
                print(f"Uploading {local_file_path} to {remote_file_path}")
                sftp.put(local_file_path, remote_file_path)
    except Exception as e:
        print(f"Failed to upload file: {e}")
    finally:
        sftp.close()
        transport.close()
        print("SFTP session closed.")

 

进行如下实验操作:

 

import os

source_path = 'D:\Develop\Python\RPAProject'
file_name = 'baseInfo_opt1.py'
target_path = "/home/cinda/ftpdata/cug_erp_test"


local_file_path = os.path.join(source_path, file_name)
print(f'local_file_path: {local_file_path}')

print(f'os.path.join(target_path, file_name): {os.path.join(target_path, file_name)}') # os.path.join()默认是在path1和path2之间添加 '\' 反斜杠, 是符合windows路径规范,但是到了Linux自然就不对了,因为Linux中路径分隔符是 '/'。

# 构建远程文件路径,注意这里不需要使用os.path.join,因为远程路径是手动指定的
remote_file_path = target_path.rstrip("/") + "/" + file_name  # .rstrip("/")就是把字符串右边的所有"/"都切除掉

print(f'remote_file_path: {remote_file_path}')

 

返回对应结果:

local_file_path: D:\Develop\Python\RPAProject\baseInfo_opt1.py
os.path.join(target_path, file_name): /home/cinda/ftpdata/cug_erp_test\baseInfo_opt1.py
remote_file_path: /home/cinda/ftpdata/cug_erp_test/baseInfo_opt1.py

 

posted @ 2024-06-01 13:25  AlphaGeek  阅读(10)  评论(0)    收藏  举报