Search code examples
pythonparamikoscp

How can I create a directory with SCPClient


I am trying to upload files to a remote server using SCPClient. It fails if the target directory does not exist

from scp import SCPClient, SCPException
...
with SCPClient(self.client.get_transport()) as scp:
    scp.put(source_path, target_path)

I am struggling to find documentation or examples that would help clarify this. Are there resources that might help?


Solution

  • I'm assuming you are using scp module for paramiko. It does not seem to support working with directories.


    If you really need to use SCP protocol, you can try scpclient library. It also does not have an explicit way to create a directory. After all, that's not what SCP protocol is designed for.

    But as your task seems to be to upload a directory – do so, upload a directory, not files:

    with closing(WriteDir(ssh_client.get_transport(), "/target/dir")) as scp:
        scp.send_dir('/source/dir')
    

    That will cause the directory to be implicitly created (if it does not exist yet) as a part of the upload.


    Though I would suggest you use SFTP protocol instead. It's built into Paramiko. So you won't need any external libraries. And SFTP supports everything you will ever need (contrary to SCP).

    See Upload files using SFTP in Python, but create directories if path doesn't exist.