【问题标题】:Python - using env variables of remote host with / SSHPython - 使用远程主机的环境变量和 / SSH
【发布时间】:2016-10-14 17:52:11
【问题描述】:

对于这个问题的任何帮助将不胜感激。

基本上,我正在编写一个 python 脚本,它将 ssh 到各种服务器并执行脚本。问题是这些脚本使用环境变量来启动。即脚本是 test.sh 但我们使用环境变量来启动它,运行 test.sh。

到目前为止,我采取的路线,例如 Paramiko 模块执行命令,但实际上并没有采用 env 变量。

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('testserver' )

stdin, stdout, stderr = ssh.exec_command(cd /home/test/;$run ./test.sh')
print stdout.readlines()
print stderr.readlines()
ssh.close()

有没有办法使用 paramiko?还是我应该采取的其他方式?

谢谢

@罗伯

我编辑了脚本进行测试。 $run 变量返回空白。

stdin, stdout, stderr = ssh.exec_command('whoami;echo hello; echo $run ; echo goodbye')

['testuser\n', 'hello\n', '\n', 'goodbye\n']
[]

@罗布第 2 部分

登录到服务器,我可以回显 $run 并返回正确的路径/脚本 我还检查了,这是在 .profile 中设置的环境变量。我觉得 python 没有调用 .profile 。

【问题讨论】:

  • 假设你修复了语法错误,当你运行上面的程序时会发生什么?
  • “脚本是 test.sh,但我们使用环境变量来启动它,运行 test.sh” 我不明白这是什么意思。如何使用环境变量来启动脚本?
  • 假设远程 shell 的 .profile 或类似的启动设置了 $run 环境变量,那应该可以正常工作。您可以通过ssh.exec_command('echo hello ; echo $run ; echo goodbye') 进行测试。
  • @JimGarrison - 线索在代码中。他的意思是$run test.sh
  • 那你还没有在远程机器上设置run环境变量。你想怎么设置run

标签: python linux ssh paramiko


【解决方案1】:

ssh.exec_command 不解释远程.profile。试试这个:

ssh.exec_command('. .profile ; cd /home/test/;$run ./test.sh')

【讨论】:

  • 嗯,那是 ./.profile 吗?它仍然为 $run 返回空白。但它不会引发任何错误。
  • 第一个命令是. .profile. ./.profile。不是./.profile
  • 太棒了,它与 一起工作。 ./.profile 感谢您的帮助!
【解决方案2】:

Plumbum 来救援。

除其他外,它提供了一个漂亮的界面,利用 paramiko(请参阅 ParamikoMachine),还允许您操作 remote environment

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多