12

I'm facing a problem that as I ssh to another machine, my paramiko ssh session does not see the same system PATH as when I manually ssh to the machine. Here is my python code:

cmd = "echo $PATH"
try:
    ssh.connect(ip, username=username, password=password)
except Exception as ex:
    raise Exception("Failed to connect to %s with credentials username='%s' password='%s' %s" \
          % (ip, username, password, ex.message) )

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
output = ssh_stdout.read()

The output show /usr/bin:/bin but when I manually ssh to the machine, there are several other paths on the system PATH. Please help.

2 Answers 2

17
+50

I don't think any bashrc or profile scripts are being sourced when you use exec_command(). Maybe try the following:

stdin, stdout, stderr = ssh.exec_command("bash -lc 'echo $PATH'")
my_path = stdout.read().rstrip()

If the problem is that you are trying to run a command that's normally in your PATH, but isn't when you use exec_command(), you're probably better off calling the command by its absolute path (run "which [command]" when you're logged into the other machine normally to find out what that is).

8

You better to load the bash_profile before you run your command. Otherwise you may get a 'command not found' exception.

For example,I write the command command = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql' in the purpose of dumping a Mysql table

Then I have to load the bash_profile manually before that dumping command by typing . ~/.profile; .~/.bash_profile;.

Example

my_command  = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql;'

pre_command = """
. ~/.profile;
. ~/.bash_profile;
"""

command = pre_command + my_command

stdin, stdout, stderr = ssh.exec_command(command)
1
  • It should fail if user has no .profile or .bash_profile
    – Slavenskij
    Commented Jun 3, 2019 at 3:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.