首页 文章

使用配置文件的ssh命令在远程机器中执行shell脚本

提问于
浏览
3

我想在远程机器上执行shell脚本,我使用下面的命令实现了这个,

ssh user@remote_machine "bash -s" < /usr/test.sh

shell脚本在远程计算机中正确执行 . 现在我在脚本中进行了一些更改,以从配置文件中获取一些值 . 该脚本包含以下行,

#!bin/bash
source /usr/property.config
echo "testName"

property.config :

testName=xxx
testPwd=yyy

现在如果我在远程机器上运行shell脚本,我没有收到这样的文件错误,因为/usr/property.config在远程机器中不可用 .

如何将配置文件与shell脚本一起传递到远程机器中执行?

2 回答

  • 3

    只有这样您才能引用您创建的 config 文件并仍然运行您的脚本,您需要将配置文件放在所需的路径上,有两种方法可以执行此操作 .

    • 如果 config 几乎总是修复而您无需更改它,请在需要运行脚本的主机上本地创建 config ,然后在脚本中放置 config 文件的绝对路径,并确保用户运行脚本有权访问它 .

    • 如果每次要运行该脚本时都需要发送配置文件,那么在发送和调用脚本之前,可能只需要 scp 该文件 .

    scp property.config user@remote_machine:/usr/property.config
    ssh user@remote_machine "bash -s" < /usr/test.sh
    

    Edit

    根据要求,如果你想在一行强行完成,这就是它的完成方式:

    • property.config
    testName=xxx
    testPwd=yyy
    
    • test.sh
    #!bin/bash
    #do not use this line source /usr/property.config
    echo "$testName"
    

    现在您可以像John建议的那样运行命令:

    ssh user@remote_machine "bash -s" < <(cat /usr/property.config /usr/test.sh)
    
  • 5

    试试这个:

    ssh user@remote_machine "bash -s" < <(cat /usr/property.config /usr/test.sh)
    

    那么你的脚本不应该在内部提供配置 .


    Second option ,如果您需要传递的只是环境变量:

    这里描述了一些技术:https://superuser.com/questions/48783/how-can-i-pass-an-environment-variable-through-an-ssh-command

    我最喜欢的也许是最简单的:

    ssh user@remote_machine VAR1=val1 VAR2=val2 bash -s < /usr/test.sh
    

    这当然意味着您需要从本地配置文件中构建环境变量赋值,但希望这很简单 .

相关问题