使用带有配置文件的 ssh 命令在远程计算机中执行 shell 脚本
Execute shell script in remote machine using ssh command with config file
我想在远程机器上执行一个 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 脚本一起传递?
试试这个:
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
这当然意味着您需要从本地配置文件构建环境变量分配,但希望这很简单。
您可以引用您创建的 config
文件并且仍然 运行 您的脚本的唯一方法是您需要将配置文件放在所需的路径中,有两种方法可以做到这一点。
如果 config
几乎总是固定的并且您不需要更改它,请在您需要 运行 的主机本地制作 config
脚本然后将 config
文件的绝对路径放入脚本中,并确保使用脚本的用户 运行 有权访问它。
如果每次想要 运行 该脚本时都需要发送您的配置文件,那么可以在发送和调用脚本之前简单地 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)
我想在远程机器上执行一个 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 脚本一起传递?
试试这个:
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
这当然意味着您需要从本地配置文件构建环境变量分配,但希望这很简单。
您可以引用您创建的 config
文件并且仍然 运行 您的脚本的唯一方法是您需要将配置文件放在所需的路径中,有两种方法可以做到这一点。
如果
config
几乎总是固定的并且您不需要更改它,请在您需要 运行 的主机本地制作config
脚本然后将config
文件的绝对路径放入脚本中,并确保使用脚本的用户 运行 有权访问它。如果每次想要 运行 该脚本时都需要发送您的配置文件,那么可以在发送和调用脚本之前简单地
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)