如何在Shell脚本中通过SSH运行功能和本地资源 [英] How to run functions and local resources over SSH in a shell script

查看:304
本文介绍了如何在Shell脚本中通过SSH运行功能和本地资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的shell脚本文件:

I have a shell script file like this:

#!/bin/bash

CONF_FILE="/tmp/settings.conf" #settings.conf contains OS_NAME="Caine Linux"
source $CONF_FILE

display_os_name() { echo "My OS is:" $OS_NAME }

#using the function locally works fine
display_os_name
#displays: My OS is: Caine Linux

#using the function on the remote host doesn't work
ssh user@host "$(declare -f); display_os_name"
#displays: My OS is:

如果我删除了-f而仅使用ssh user@host "$(declare); display_os_name",它可以工作,但显示以下错误和警告:

If I remove the -f and I use just ssh user@host "$(declare); display_os_name" it works but displays these errors and warnings:

bash: line 10: BASHOPTS: readonly variable
bash: line 18: BASH_VERSINFO: readonly variable
bash: line 26: EUID: readonly variable
bash: line 55: PPID: readonly variable
bash: line 70: SHELLOPTS: readonly variable
bash: line 76: UID: readonly variable

如果我使用ssh user@host "$(declare); display_os_name >/dev/null"禁止显示警告,则仅禁止显示函数的输出(我的操作系统为:Caine Linux),而不显示警告.

If I use ssh user@host "$(declare); display_os_name >/dev/null" to suppress the warnings only the output of the function is suppressed (My OS is: Caine Linux), not the warnings.

是否可以在远程SSH主机上与本地源文件一起运行本地功能?

Is there a way to run local functions together with sourced local files on a remote SSH host?

推荐答案

一种简单的方法(如果您的本地系统是Linux)是在您的source命令之前使用set -a启用自动导出;在标准输入上复制/proc/self/environ;并将其解析为一组远程变量.

An easy approach (if your local side is Linux) is to use set -a to enable automatic export before your source command; copy /proc/self/environ on stdin; and parse it into a set of variables on the remote side.

由于BASHOPTSEUID等不是环境变量,因此可以避免尝试对其进行修改. (如果您遵守 POSIX建议,并为您使用小写名称自己的变量,甚至可以完全忽略所有大写字母的变量.)

Because BASHOPTS, EUID, etc. aren't environment variables, this avoids trying to modify them. (If you were complying with POSIX recommendations and using lowercase names for your own variables, you could even go as far as to ignore all-caps variables entirely).

set -a # enable export of all variables defined, **before** the source operation
source /tmp/settings.conf

import_env() {
  while IFS= read -r -d '' item; do
    printf -v "${item%%=*}" "%s" "${item#*=}" && export "$item"
  done
}

cat /proc/self/environ | ssh user@host "$(declare -f); import_env; display_os_name"

更容易的是只是通过网络复制要获取的文件.

Even easier is to just copy the file you want to source over the wire.

ssh user@host "$(declare -f); $(</tmp/settings.conf); display_os_name"

这篇关于如何在Shell脚本中通过SSH运行功能和本地资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆