Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python paramiko ssh session does not get the system path

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.

like image 237
max Avatar asked Jul 15 '13 18:07

max


2 Answers

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).

like image 65
brjaga Avatar answered Nov 07 '22 21:11

brjaga


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)
like image 8
Marvin W Avatar answered Nov 07 '22 19:11

Marvin W