0

I am interested if there is any way to change current working directory on remote server by using subprocess or pxssh modules. The purpose for this is to make new directories, and copy/paste files. Also, it would be useful for me to know if there is any way to do these things in one single process. Executing command below does not help me because process terminates immediately after command execution is completed.

import subprocess
p=subprocess.Popen(['ssh', '15.27.23.2','cd /home/incoming'], shell=True)
p.wait()

Does anyone know way to do this? No third part libraries should be used. Thanks for any help.

user5142625
  • 85
  • 1
  • 1
  • 9
  • if you are on POSIX then don't use `shell=True` with a list argument; use a single string (the shell command) or drop `shell=True`. – jfs Aug 02 '15 at 00:10
  • you could [use `pexpect` to run multiple commands (communicate with the remote shell via ssh)](http://stackoverflow.com/a/15913906/4279). Or use `paramiko.SFTPClient` to perform file operations. – jfs Aug 02 '15 at 00:40
  • [paramiko's code example: download all files from a remote folder -- it shows how to change local/remote directories](http://stackoverflow.com/a/20381739/4279). Here's another [paramiko's code example: it shows how to create remote directories](http://stackoverflow.com/a/20294079/4279) – jfs Aug 02 '15 at 00:46
  • Sorry J.F.Sebastian. My mistake. – nv_wu Aug 02 '15 at 10:52
  • I guess provided you have the shell arg set, you could build a string of commands using a semicolon like the following post: [running multiple bash command with subprocess](http://stackoverflow.com/questions/17742789/running-multiple-bash-commands-with-subprocess). – nv_wu Aug 02 '15 at 11:16

1 Answers1

2

As you observe, the program creates an SSH connection to the remote host where it runs a shell and then (because there are no further commands) immediately terminates. Each process has its own "current directory," including the process you run on the remote machine.

Clearly one way would be send a longer command string, which includes a mkdir, a cd and then the command(s) you want to run.

A better way would be to investigate the use of fabric, which has facilities to allow you to run arbitrary remote commands in the required context. The specific problem you face is addressed on this documentation page, and that alone might show you how to proceed using commands like mkdir project && cd project && do-something.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • I would like to create new folder on /home/incoming, copy/paste files and execute programs on that location. Is there any way to do it in one process? – user5142625 Aug 01 '15 at 08:13
  • Yeah, I understand that I made mistake when I said that "Nothing happens" – user5142625 Aug 01 '15 at 08:15