使用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
使用scp - anishsane
@anishsane:当目标不是复制时,为什么要使用scp - sjsam
scp是将文件传输到目标的最可靠方式。还有其他选项,比如通过stdin发送它(ssh user@remote_host 'cat >/path/to/config.file; /remote/command' < /local/config.file),但是scp是最可靠的方式。 - anishsane
2个回答

5

如果你创建了一个config文件,希望在运行脚本时引用它,并且需要将config文件放置到所需路径中,那么有两种方法可以实现。

  1. If config is almost always fixed and you need not to change it, make the config locally on the host machine where you need to run the script then put the absolute path to the config file in your script and make sure the user running the script has permission to access it.

  2. If need to ship your config file every time you want to run that script, then may just simply scp the file before you send and call the script.

    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需要执行多个命令。是否可能将它们合并为单个命令? - Jugi
你可以这样做 scp property.config user@remote_machine:/usr/property.config;ssh user@remote_machine "bash -s" < /usr/test.sh 但如果你真的想将它们组合成单个命令,那么你将不得不在单个文件中使用 cat 命令来输出 configbash 脚本的内容(正如 @John 所提到的),这需要对 test.sh 的源代码进行一些小的更改。如果你有兴趣更改它,我也可以分享这种方法。 - anand
谢谢Anand。我已经按预期使其工作,但我仍然很好奇是否有更多选项可供选择。请分享您的方法。 - Jugi
@Jugi 我已经更新了答案,描述了另一种技术。 - anand
谢谢。我的最后一个问题是,如何传递参数给它? - Jugi
@Jugi 不需要传递任何参数,因为 config 文件(我假设它也是用 bash 脚本语法编写的)已经与 bash 脚本合并成一个单独的自包含脚本,可以在远程机器上执行而不需要任何依赖项。 - anand

3

试试这个:

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

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

谢谢。配置文件包含更多的属性值集合。它就像一个包装器配置文件,定义了配置文件中的所有值,并根据此执行脚本。将所有这些值作为参数传递似乎有点困难。 - Jugi
在运行 ssh user@remote_machine "bash -s" < (cat source /usr/property.config /usr/test.sh) 时出现了 -bash: syntax error near unexpected token '(' 的错误。 - Jugi
1
@anishsane 第二行应该是 ssh user@remote_machine "bash -s" < <(cat /usr/property.config /usr/test.sh)。"source" 未定义,不能这样使用,我猜可能打错了。 - anand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接