简体   繁体   English

python paramiko ssh session没有得到系统路径

[英]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. 我遇到一个问题,当我ssh到另一台机器时,我的paramiko ssh会话看不到与我手动ssh到机器时相同的系统路径。 Here is my python code: 这是我的python代码:

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. 输出显示/ usr / bin:/ bin但是当我手动ssh到机器时,系统PATH上还有其他几个路径。 Please help. 请帮忙。

I don't think any bashrc or profile scripts are being sourced when you use exec_command(). 我不认为在使用exec_command()时会获取任何bashrc或profile脚本。 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). 如果问题是你正在尝试运行一个通常在你的PATH中的命令,但是当你使用exec_command()时,你可能最好用它的绝对路径调用命令(运行“which [command]”)当你正常登录到另一台机器时,找出它是什么)。

You better to load the bash_profile before you run your command. 最好在运行命令之前加载bash_profile。 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 例如,我为了转储Mysql表而编写命令command = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql'

Then I have to load the bash_profile manually before that dumping command by typing . ~/.profile; .~/.bash_profile; 然后我必须通过键入在该转储命令之前手动加载bash_profile . ~/.profile; .~/.bash_profile; . ~/.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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM