OSError: [Errno 22] Invalid argument (Paramiko)

OSError: [Errno 22] Invalid argument (Paramiko)

我将使用 Paramiko 执行 sftp 将文件从 Linux 环境传输到 Windows。

我在 Stack Overflow 上尝试了不同的解决方案,但仍然遇到同样的问题。

我的脚本

localpath = os.path.join(os.sep, 'Users', 'me', 'Desktop', 'ELK', 'PM_XML')
serverpath = r"***/****/***"
def sftp():
    ip=ipAddr.get()
    while True:
        current_time = time.time()
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,username="root",password="root")
        sftp = ssh.open_sftp()
        for element in sftp.listdir(serverpath):
            if element.endswith(".xml"):
                creation_time = sftp.stat(serverpath+element).st_mtime
                if (current_time+3400 - creation_time) / (3600) <= 1:
                    sftp.get(serverpath+element,os.path.join(os.sep,localpath,element))
        sftp.close()
        ssh.close()

我收到这个错误:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "C:\Users\me\AppData\Local\Programs\Python\Python37-32\lib\site-packages\paramiko\sftp_client.py", line 801, in g
et
    with open(localpath, "wb") as fl:
OSError: [Errno 22] Invalid argument: '\Users\me\Desktop\ELK\PM_XML\A2018-10-18T11:03:00+02:00-2018-10-18T11:04:00
+02:00_user-67-0-test-vm2.lk.fr.xml'

我认为问题出在文件名上

A2018-10-18T11:03:00+02:00-2018-10-18T11:04:00 +02:00_user-67-0-test-vm2.lk.fr.xml'

因为当我尝试使用简单的文件名执行此操作时,我的脚本工作正常。

关于处理此文件名的任何建议,因为我想保留在服务器上使用的相同名称。

由 Martin Prikryl 解决 建议将冒号“:”替换为“_”

element.replace(":","_")

在 Windows 上,文件名不能包含冒号 (:) 和其他特殊字符。

关于 Naming Conventions 的 Microsoft 文档:

Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

  • ...

  • : (colon)

  • ...


对此你无能为力。