You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过SSH在本地Bash脚本中获取远程主机变量

解决办法

首先得搞定SSH免密登录,不然脚本没法自动运行(总不能每次手动输密码):

  1. 在本地生成SSH密钥对:
ssh-keygen -t ed25519

一路回车就行,别设密码。

  1. 把公钥传到远程主机(替换成你的远程用户名和IP):
ssh-copy-id remote_user@192.168.x.x

第一次输远程主机的用户密码,之后就不用了。

接下来修改你的脚本,把需要从远程获取变量的部分,全部改成通过SSH在远程执行命令,把结果传回本地。具体修改如下:

#!/bin/sh

MAX_TEMP_CPU=80
MAX_TEMP_24=60
MAX_TEMP_5=60

# Email settings (mail envelope) #
FROM_ADDRESS="someaddress"
TO_NAME="name"
TO_ADDRESS="address"

# Email credentials #
USERNAME="email"
PASSWORD="password"

# Server settings #
SMTP="smtp.gmail.com"
PORT="465"

# 这里的productid也从远程获取,如果你需要的话
FROM_NAME="Router $(ssh remote_user@192.168.x.x 'nvram get productid')"

# set environment PATH to system binaries #
export PATH=/sbin:/bin:/usr/sbin:/usr/bin:$PATH

# --------------------------
# 从远程主机获取变量的SSH逻辑
# 替换成你的远程用户名和IP
REMOTE_SSH="ssh remote_user@192.168.x.x"
# --------------------------

# 远程执行命令,捕获结果到本地变量
wifi24_status=$($REMOTE_SSH 'nvram get wl0_ifname')
wifi5_status=$($REMOTE_SSH 'nvram get wl1_ifname')

cpu_temp=$($REMOTE_SSH 'cat /sys/class/thermal/thermal_zone0/temp | sed "s/[^0-9]//g" | awk "{print int( \$1 / 1000 +0.5)}"')

# 获取wifi温度时,直接在远程执行完整命令(避免本地传递变量的麻烦)
wifi24_temp=$($REMOTE_SSH 'wl -i $(nvram get wl0_ifname) phy_tempsense | awk "{print int(\$1 / 2 + 20 +0.5)}"')
wifi5_temp=$($REMOTE_SSH 'wl -i $(nvram get wl1_ifname) phy_tempsense | awk "{print int(\$1 / 2 + 20 +0.5)}"')


if [ $cpu_temp -gt $MAX_TEMP_CPU -o $wifi24_temp -gt $MAX_TEMP_24 -o $wifi5_temp -gt $MAX_TEMP_5 ]; then
  msg="Temperature too hot, CPU: $cpu_temp/$MAX_TEMP_CPU DegC 2.4Ghz wifi: $wifi24_temp/$MAX_TEMP_24 DegC 5Ghz wifi: $wifi5_temp/$MAX_TEMP_5 DegC"

# notify Syslog of the event
#logger $msg

# assemble the message
echo "From: \"$FROM_NAME\" <$FROM_ADDRESS>" > /tmp/mail.txt
echo "To: \"$TO_NAME\" <$TO_ADDRESS>" >> /tmp/mail.txt
echo "Subject: $msg" >> /tmp/mail.txt
echo "Date: $(date -R)" >> /tmp/mail.txt
echo "" >> /tmp/mail.txt
echo "--- " >> /tmp/mail.txt
echo "Your friendly home router $($REMOTE_SSH 'nvram get productid')." >> /tmp/mail.txt

# send with curl
curl --url smtps://$SMTP:$PORT \
--mail-from "$FROM_ADDRESS" --mail-rcpt "$TO_ADDRESS" \
--upload-file /tmp/mail.txt \
--ssl-reqd \
--user "$USERNAME:$PASSWORD"

# remove temp file
rm /tmp/mail.txt
fi

注意事项:

  • 把脚本里的remote_user@192.168.x.x替换成你实际的远程主机用户名和IP地址
  • 如果远程主机的SSH端口不是默认22,要在REMOTE_SSH里加上端口参数:ssh -p 自定义端口 remote_user@192.168.x.x
  • 确保远程主机上的nvram、wl、awk、sed这些命令都存在,并且路径正确(如果不在默认PATH里,就写绝对路径,比如/sbin/nvram)

内容的提问来源于stack exchange,提问作者Ruf1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:04:56