【问题标题】:Execute shell script in remote machine using ssh command with config file使用带有配置文件的 ssh 命令在远程机器上执行 shell 脚本
【发布时间】:2016-03-28 16:24:24
【问题描述】:

我想在远程机器上执行一个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 脚本一起传递?

【问题讨论】:

  • 使用scp ?
  • @anishsane :当目标不是复制时,为什么要使用scp
  • scp 是使文件成为目标的最可靠方法。还有其他选择,比如通过stdin (ssh user@remote_host 'cat &gt;/path/to/config.file; /remote/command' &lt; /local/config.file) 发送,但 scp 是最可靠的方式。

标签: linux bash shell ssh scp


【解决方案1】:

试试这个:

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

那么您的脚本不应在内部获取配置。


第二个选项,如果你只需要传递环境变量:

这里描述了一些技术: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

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

【讨论】:

  • 谢谢.. 配置文件包含更多的属性值。它就像一个包装配置文件,用于定义配置文件中的所有值并基于此执行脚本。将所有这些值作为参数传递似乎有点困难
  • -bash: 意外标记附近的语法错误('. Getting this error while running ssh user@remote_machine "bash -s"
  • @anishsane 第二行应该是ssh user@remote_machine "bash -s" &lt; &lt;(cat /usr/property.config /usr/test.sh) source 是未定义的,不能这样使用,我认为这是一个错字。
【解决方案2】:

您可以引用您创建的 config 文件并仍然运行您的脚本的唯一方法是您需要将配置文件放在所需的路径中,有两种方法可以做到这一点。

  1. 如果config 几乎总是固定的并且您不需要更改它,请在需要运行脚本的主机上本地创建config,然后将绝对路径放入config 文件在您的脚本中,并确保运行该脚本的用户有权访问它。

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

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

编辑

根据要求,如果您想在一行中强制执行,可以这样做:

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

【讨论】:

  • 谢谢.. #2 需要执行多个命令.. 是否可以合并为单个命令.,.?
  • 你可以这样做 scp property.config user@remote_machine:/usr/property.config;ssh user@remote_machine "bash -s" &lt; /usr/test.sh 但这是 作弊 如果你真的想将它们组合为单个命令,那么你将不得不 cat 的输出configbash 单个文件中的脚本(正如@John 所提到的)如果你愿意的话,我可以分享这个方法,如果你有兴趣改变它,我也可以分享这个方法。
  • 谢谢阿南德。我得到了它按预期工作,但我仍然很想得到更多的选择。请分享你的方法。
  • @Jugi 我已经更新了描述其他技术的答案。
  • 谢谢.. 我的最后一个问题,如何将参数传递给那个:(?
猜你喜欢
  • 2011-04-26
  • 1970-01-01
  • 2017-11-24
  • 2012-12-05
  • 2016-03-07
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多