I'm trying to retrieve environment variables of a remote Linux server in Python. Alternatively, if I could use the variable name in the command I'm executing, that'd be great as well. The calls I'm making should work, as far as I can tell, but I'm getting back garbage. I have set up public-key authentication, so no password required.
Effort 1:
devdir = subprocess.check_output(["ssh", connectstring, "echo $DEVDIR"])
Effort 2:
ret = subprocess.check_output(["ssh", connectstring, 
    "$DEVDIR/{0}".format(testpath)])
connectstring is user@ip and works fine. $DEVDIR is the remote variable I want to use and contains a path. testpath is the path to the script I'm trying to execute, rooted at $DEVDIR.
Effort 1 returns "\n", Effort 2 fails to resolve $DEVDIR remotely.
Effort 3:
import paramiko
...
ssh = paramiko.SSHClient()
ssh.connect(ip, user)    # succeeds
stdin, stdout, stderr = ssh.exec_command("echo $DEVDIR")
result: stdout.readlines() = "\n"
If the environment variable is set in .bashrc, you can force the remote command to run under a login shell with the -l option. The following...
devdir = subprocess.check_output(["ssh", connectstring, "sh -l -c 'echo $DEVDIR'"])
...works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With