Python – pysftp connection change directory does not work

pysftp connection change directory does not work… here is a solution to the problem.

pysftp connection change directory does not work

I tried the following three ways to change the directory, but it never changes. Has anyone else encountered this issue?

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. I’ve tried many other combinations, but I don’t list them here.

It doesn’t mean anything to me, can you help?

Solution

Try chdir() instead. According to the documentation:

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

Related Problems and Solutions