2013-07-15 37 views
5

我面臨一個問題,因爲我ssh到另一臺機器,我的paramiko ssh會話沒有看到相同的系統路徑,當我手動ssh到機器。 這裏是我的Python代碼:蟒蛇paramiko ssh會話沒有得到系統路徑

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

輸出顯示在/ usr/bin中:/ bin中 但是當我手動ssh到機器,也有對系統PATH其他幾個路徑。 請幫忙。

回答

5

當您使用exec_command()時,我不認爲任何bashrc或配置文件腳本正在源。也許嘗試以下操作:

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

如果問題是,你正在嘗試運行一個命令,就是在正常的路徑,但不是當你使用exec_command(),你可能會更好過調用命令通過它的絕對路徑(當你正常登錄另一臺機器時運行「which [命令]」以查明它是什麼)。

3

您最好在運行命令之前加載bash_profile。否則,您可能會收到'command not found'異常。

例如,我寫的命令command = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql'在傾倒MySQL表

然後,我有到傾倒命令之前通過鍵入. ~/.profile; .~/.bash_profile;手動加載.bash_profile中的目的。

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)