【问题标题】:python paramiko ssh session does not get the system pathpython paramiko ssh会话没有获取系统路径
【发布时间】:2013-07-13 18:07:39
【问题描述】:

我面临一个问题,当我 ssh 到另一台机器时,我的 paramiko ssh 会话没有看到与我手动 ssh 到机器时相同的系统 PATH。 这是我的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()

输出显示 /usr/bin:/bin 但是当我手动 ssh 到机器时,系统 PATH 上还有其他几个路径。 请帮忙。

【问题讨论】:

    标签: python path system paramiko


    【解决方案1】:

    您最好在运行命令之前加载 bash_profile。否则,您可能会收到“找不到命令”异常。

    例如,我写了command = 'mysqldump -uu -pp -h1.1.1.1 -P999 table > table.sql'这个命令,目的是为了转储一个Mysql表

    然后我必须在转储命令之前手动加载 bash_profile,方法是键入 . ~/.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)
    

    【讨论】:

    • 如果用户没有 .profile 或 .bash_profile 应该会失败
    【解决方案2】:

    我认为当您使用 exec_command() 时不会获取任何 bashrc 或配置文件脚本。不妨试试以下方法:

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

    如果问题是你试图运行一个通常在你的 PATH 中的命令,但当你使用 exec_command() 时却没有,你最好通过它的绝对路径调用命令(运行“which [ command]" 当您正常登录到另一台机器以找出它是什么时)。

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2010-12-27
      • 2017-08-27
      • 2016-06-12
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多