通过在命令行上传递远程主机参数和脚本参数,在远程主机上执行本地脚本



有人知道是否有语法可以在本地主机上传递远程主机参数(用户和IP/主机名(和脚本参数,并使其在远程主机上执行吗?

我不是这样想的:$ ssh user@remoteServer "bash -s" -- < /path/script.ssh -a X -b Y

相反,我希望脚本能够像这样传递:$/path/script.ssh user@remoteServer -a X -b Y

但我不确定如何在剧本中实现这种行为:

[...] script [...]
connect to user@remoteServer
[...] execute the script code (on the remote host) [...]
end of script

有什么建议吗?我需要换一种方式来处理这个问题吗?

编辑

我已经设法让脚本在通过SSH连接后执行一些东西,但我有点不明白为什么有些命令在传递到远程主机终端之前就被执行了;我的代码现在是这样的:


while getopts 'ha:u:d:s:w:c:' OPT; do
case $OPT in
a) host=$OPTARG;;
u) user=$OPTARG ;;
d) device=$OPTARG ;;
s) sensor=$OPTARG ;;
w) warn_thresh=$OPTARG ;;
c) crit_thresh=$OPTARG ;;
h) print_help
*) printf "Wrong option or valuen"
print_help
esac
done
shift $(($OPTIND - 1))
# Check if host is reachable
if (( $# )); then
ssh ${user}@${host} < $0
# Check for sensor program or file
case $device in
linux)  do things
raspberry) do things
amlogic)  do things
esac
# Read temperature information
case $device in
linux)  do things
raspberry)      do things
amlogic)   do things
esac

# Check for errors
if (())
then
# Temperature above critical threshold
# Check for warnings
elif (())
then
# Temperature above warning threshold
fi
# Produce Nagios output
printf [......]
fi

脚本运行起来似乎没有问题,但我没有得到任何输出。

一个简单的例子-

if (( $# ))          # if there are arguments 
then ssh "$1" < $0   # connect to the first and execute this script there
else whoami          # on the remote, there will be no args...
uname -n        # if remote needs arguments, change the test condition
date            # these statements can be as complex as needed
fi

我的示例脚本只是将目标系统登录作为它的第一个参数
运行它时不带任何参数,它输出当前系统的数据;使用登录,它在那里运行。

如果您使用授权密钥进行无密码登录,则会非常顺利,否则会提示您。

只需分析您的论点并采取相应的行为。:(

如果需要远程上的参数,请使用更复杂的测试来决定采用哪个分支。。。

编辑2

我重复一遍:如果您需要远程参数,请使用更复杂的测试来决定要使用哪个分支

while getopts 'ha:u:d:s:w:c:' OPT; do
case $OPT in
a) host=$OPTARG;;
u) user=$OPTARG ;;
d) device=$OPTARG ;;
s) sensor=$OPTARG ;;
w) warn_thresh=$OPTARG ;;
c) crit_thresh=$OPTARG ;;
h) print_help
*) printf "Wrong option or valuen"
print_help
esac
done
shift $(($OPTIND - 1))
# handoff to remote host
if [[ -n "$host" ]]
then scp "${user}@${host}:/tmp/" "$0"
ssh "${user}@${host}" "/tmp/${0##*/} -d $device -s $sensor -w $warn_thresh -c $crit_thresh" 
exit $?
fi
# if it gets here, we're ON the remote host, so code accordingly
# Check for sensor program or file
case $device in
linux)  do things
raspberry) do things
amlogic)  do things
esac
# Read temperature information
case $device in
linux)  do things
raspberry)      do things
amlogic)   do things
esac

# Check for errors
if (())
then
# Temperature above critical threshold
# Check for warnings
elif (())
then
# Temperature above warning threshold
fi
# Produce Nagios output
printf [......]
fi

最新更新