加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

源环境变量并在远程机器上运行本地脚本之前执行bash [复制]

发布时间:2020-12-15 22:38:37 所属栏目:安全 来源:网络整理
导读:参见英文答案 Pass commands as input to another command (su,ssh,sh,etc)????????????????????????????????????3个 我正在尝试使用ssh连接执行远程本地脚本.我已经阅读了有关它语法的文档.但我的问题是,在运行脚本之前,我需要执行bash和源环境变量. 这看起
参见英文答案 > Pass commands as input to another command (su,ssh,sh,etc)????????????????????????????????????3个
我正在尝试使用ssh连接执行远程本地脚本.我已经阅读了有关它语法的文档.但我的问题是,在运行脚本之前,我需要执行bash和源环境变量.

这看起来适合我,但它没有源命令:

ssh [user]@[server] 'bash -s' < [local_script]

我用EOF尝试过这样的东西,但它对我也不起作用:

#!/bin/bash
/usr/bin/ssh  "$user@$$host" <<EOF
bash -s
source /dir/to/profile/.profile
source /dir/to/env/set/env.sh
/path/to/script/script.sh stop
EOF

您对这种远程命令的实现有什么想法吗?我必须在环境设置之前获取配置文件,否则它会给出异常.但主要问题是关于来源.

也许这是一个简单的问题,但我没有任何想法.提前感谢您的所有答案.

解决方法

eval可以为您完成此任务:

eval $(cat /path/to/environment) ./script.sh

如果你知道的话,你可以用这种方式获取多个文件
路径:

eval $(cat /path/to/environment1 /path/to/environment2) ./script.sh

或者遍历目录:

eval $(cat $(find -type f /path/to/environments)) ./script.sh

如果您正在远程执行此操作以解决您的特定问题,请在其前面粘贴SSH:

# note the quotes otherwise we'll source our local environment
ssh user@host "'eval $(cat /path/to/environment)' ./remote_script.sh"

# If it's a local environment you want to sort,then do the same
# command without the quotes:
ssh user@host "eval $(cat /path/to/environment)" ./remote_script.sh

如果要将远程环境发送到自己的环境中,请使用eval
本地如此:

eval "$(ssh user@host cat /path/to/environment)" ./local_script.sh

这需要您来源外部文件,将其环境变量设置在同一个分叉实例中,该实例将调用您的脚本(使其可用).

考虑一个如下所示的脚本文件:

#!/bin/sh
echo "$VAR1"
echo "$VAR2"
test_function

现在考虑您的环境文件如下所示:

# Environment Variables
VAR1=foo
VAR2=bar
test_function()
{
   echo "hello world"
}

如果使用eval示例,您将看到输出:

foo
bar
hello world

或者,如果您只是打开您编写的脚本,则可以提供源代码
这些环境变量直接来自它,然后就可以了
正常调用脚本没有任何技巧:

#!/bin/sh

# Source our environment by starting with period an then following
# through with the full path to the environment file. You can also use
# the 'source' keyword here too instead of the period (.).
. /path/to/environment

echo "$VAR1"
echo "$VAR2"
test_function

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读