Use Environment Variable In SFTP Path In Paramiko

- 1 answer

I'm running a script on my server and trying to get some files from my Firewall. I get a "file not found" error when referring to the file using an environment variable ($ sign). B, but I can get my file when I enter a normal path. I'm aware that the code doesn't look good, this is just an quick example. Here is my working code:

_savedLocation = "/home/kartal/Desktop/aaa.tgz"
folder, savedLocation = os.path.split(_savedLocation)
remotepath = "$FWDIR/bin/upgrade_tools/"
remotefile = remotepath + savedLocation
stdin, stdout, stderr =
  ssh.exec_command("cd {} && yes | ./migrate export {} ".format(remotepath, savedLocation))
command = "cd {} && chmod 777 {}".format(remotepath, savedLocation)
stdin, stdout, stderr = ssh.exec_command(command)
sftp = ssh.open_sftp()
sftp.get(remotefile, _savedLocation)

If I use real path as remotepath = "/opt/r80/fw1/bin/upgrade_tools/", the code works.

Btw, I'm running the "migrate" script in the first step with $FWDIR. So $FWDIR works with exec_command, but not in SFTP get.

Where am I doing wrong and what should I do?



You cannot use environment variables in SFTP. You have to use real paths. In this case the real path is /opt/CPsuite-R80/fw1.

If the real path is not fixed, and you really need to obtain the real path from a variable value, you will need to resolve the variable value using a different interface (e.g. using a shell access). And then use the resolved value in SFTP. This is what you do in WinSCP - you execute cd $FWDIR in the shell. And the shell resolves $FWDIR to /opt/CPsuite-R80/fw1. In Paramiko, you can use SSHClient.exec_command to resolve the variable:

stdin, stdout, stderr = ssh.exec_command("echo $FWDIR")
fwdir =