是否有人知道是否有一种语法可以将远程主机参数(用户和 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 连接后执行something,但我有点不明白为什么在将某些命令传递到远程主机终端之前执行它们;我的代码目前看起来像这样:
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 value\n"
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
脚本似乎运行没有问题,但我没有输出。
答案 0 :(得分:1)
一个简单的例子 -
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
我的示例脚本仅将目标系统登录名作为其第一个参数。
不带参数运行它,它输出当前系统的数据;使用登录名,它会在那里运行。
如果您使用授权密钥进行无密码登录,则非常顺畅,否则会提示您。
只需解析您的参数并采取相应的行动。 :)
如果您需要远程参数,请使用更复杂的测试来决定采用哪个分支...
我再说一遍:如果您需要远程参数,请使用更复杂的测试来决定采用哪个分支...
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 value\n"
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