How do I change directories using Paramiko?

Mike Ryan picture Mike Ryan · Jan 19, 2012 · Viewed 31.2k times · Source

Drush commands not executing using Paramiko

I posted the above question regarding a persistent error message that I receive using Paramiko. I do not think it is related to my next question, but it might be.

I can successfully connect to my server via SSH using Paramiko. I can execute commands like ls or pwd. What I can't seem to do is change directories. I can send the command "cd .." for example, but when I follow up with "pwd" it shows that I haven't changed directories. It just lists the initial directory I am in when I log in.

>>> stdin, stdout, stderr = myssh.exec_command("pwd")
>>> stdout.readlines()
['/big/dom/home/myid\n']
>>> stdin, stdout, stderr = myssh.exec_command("cd ../")
>>> stdout.readlines()
[]
>>> stdin, stdout, stderr = myssh.exec_command("pwd")
>>> stdout.readlines()
['/big/dom/home/myid\n']
>>>

Am I misunderstanding what is going on here? Should I not be able to change directories? Or if I can, should I be doing it in some other way than using exec_command?

Answer

Mike Ryan picture Mike Ryan · Jul 30, 2012

This guy had it figured out: http://www.vertigrated.com/blog/2010/02/python-remote-ssh-with-paramiko/

You just have to send multiple commands with one exec_command, such as:

myssh.exec_command('cd ..; pwd')

Then stdout.readlines() will return the directory that you changed to.