Search code examples
pythonsshcdpysftp

pysftp connection change directory doesn't work


I've tried the following three ways to change a directory and it never changes. has anyone else had this problem?

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
host = 'server1.mydomain.com' # altered
with pysftp.Connection(host=host, **get_credentials(), cnopts=cnopts) as connection:

    connection.execute('cd project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    connection.execute('cd /home/jm/project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    connection.cd('project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    with connection.cd('project'):
        print(connection.execute('pwd'))  #---> [b'/home/jm\n']

'/home/jm/project/' does exist by the way. I've also trid many other combinations that I didn't list here.

It doesn't make any sense to me, can you help?


Solution

  • Try chdir() instead. Per the docs:

    cd(remotepath=None)
    context manager that can change to a optionally specified remote directory and restores the old pwd on exit.
    
    chdir(remotepath)
    change the current working directory on the remote
    

    So:

    connection.chdir('/home/jm/project')