Search code examples
pythonsftpfabric

Create remote directory using fabric.operations.put()


I need to put some files onto a remote sftp server, creating a new directory to put them in. Is there a way to do this using fabric? Fabric.operations.put() doesn't look like it can handle creating the new directory on the remote side.


Solution

  • Run mkdir before calling put():

    run('mkdir -p /path/to/dir/')
    
    put('/local/path/to/myfile', '/path/to/dir/')
    

    -p flag handles creating nested directories, see:

    -p, --parents

    no error if existing, make parent directories as needed


    Update (for sftp-only access).

    Using SFTP.mkdir():

    from contextlib import closing
    from fabric.sftp import SFTP
    
    ftp = SFTP(env.host_string)
    with closing(ftp) as ftp:
        ftp.mkdir('/path/to/dir/', use_sudo=False)
    
    put('/local/path/to/myfile', '/path/to/dir/')