OSError: [Errno 22] Invalid argument (Paramiko)

Question:

I ma using Paramiko to do a sftp to transfer file from Linux environment to Windows.

I tried different solutions on Stack Overflow but still having the same problem.

My script

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()

I am getting this error:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "C:UsersmeAppDataLocalProgramsPythonPython37-32libsite-packagesparamikosftp_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'

I think the problem is due to the file name

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

because when I try to do that with a simple filename my script works fine.

Any suggestions to deal with this filename, because I would like to keep the same name used on the server.

Solved by Martin Prikryl
a suggestion replace colon “:” with “_”

element.replace(":","_")
Asked By: C.med

||

Answers:

On Windows, a filename cannot contain a colon (:), among other special characters.

Microsoft documentation on Naming Conventions:

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)


There’s nothing you can do about it, except for removing/replacing the colon from the filename.

Answered By: Martin Prikryl