Android WireGuard Magisk 的使用
2023年11月1日 · 880 字 · 2 分钟
之前手机已经安装了 magisk 和 magisk-ssh-modules。通过 ssh
传输文件(scp\rsync),安装软件(pm install),非常地方便。但是手机不同于服务器,没有固定 ip,所以说“很方便”也有有点勉强。那需求来了,如何给手机一个固定 IP 呢?
需求
给手机一个固定的 ip,支持流量和不同 wifi 等网络情况。
办法
首先排除,在 wifi 网络中设置静态 IP 这个方法,此方法不能用于流量,而且每个 wifi 环境都得设置一遍,麻烦。而且有些 wifi 提供的网段并非你能选择。
尝试使用 WireGuard,将树莓派,手机,办公电脑,生活电脑等设备,永远组建在一个内网环境中。
- 树莓派,24*7 在线,有公网地址(DDNS),配置 wireguard 地址 10.10.0.1
- 电脑,wireguard 地址 10.10.0.2
- 手机,wireguard 地址 10.10.0.3
- 电脑,wireguard 地址 10.10.0.4
这样我们就给手机分配了一个固定 ip,内网设备,ssh 直连手机; 外网设备,通过树莓派可以中转 ssh 到手机。
补充
有个麻烦的问题,家里内网环境下,不支持通过公网 ip 访问内网设备。这里涉及到 NAT 回流的问题。这个问题有一些解决方案,比如内网自建 DNS 服务。
我没有自建 DNS 服务,而是通过判断手机 wifi 切换时,是否是连上家里的 wifi。如果是,则用树莓派的内网地址,如果不是,则用树莓派的公网地址。此方法参考开源项目。
我的检测脚本如下:
#!/system/bin/sh
until [ $(getprop init.svc.bootanim) = "stopped" ] ; do
sleep 2
done
service_path=`realpath $0`
module_dir=`dirname ${service_path}`
/system/bin/echo "" >> $module_dir/log.txt
write_log() {
time=$(date '+%Y-%m-%d %H:%M:%S')
/system/bin/echo "$time : $*" >> $module_dir/log.txt
# /system/bin/echo "$time : $*"
}
write_log "wg service start ..."
sleep 20
notif() {
write_log "try notif $*"
su -lp 2000 -c "/system/bin/cmd notification post -S bigtext -t 'WireGuard AutoConnect Service' 'Tag' \"$*\"" < /dev/null > /dev/null 2>&1
}
stop_wg0() {
# write_log "try to disconnect the wg0"
if [ -z "$(/system/bin/wg show wg0)" ]; then
return
fi
write_log "run wg-quick down wg0"
/system/bin/wg-quick down wg0
}
start_wg0() {
# write_log "try to connect the wg0"
if [ -z "$(/system/bin/wg show wg0)" ]; then
stop_wg1
write_log "not connected to home network"
write_log "run wg-quick up wg0"
up_result=$(/system/bin/wg-quick up wg0)
if [[ $? != '0' ]]; then
notif $up_result
else
notif "start wg0 ok"
fi
fi
}
stop_wg1() {
# write_log "try to disconnect the wg1"
if [ -z "$(/system/bin/wg show wg1)" ]; then
return
fi
write_log "run wg-quick down wg1"
/system/bin/wg-quick down wg1
}
start_wg1() {
# write_log "try to connect the wg1"
if [ -z "$(/system/bin/wg show wg1)" ]; then
stop_wg0
write_log "matched [$ssid_matched], connected to home network"
write_log "run wg-quick up wg1"
up_result=$(/system/bin/wg-quick up wg1)
if [[ $? != '0' ]]; then
notif $up_result
else
notif "start wg1 ok"
fi
fi
}
/system/bin/nohup ip monitor dev wlan0 | while read event; do
ssid_matched=$(cmd wifi status | grep connected.*2103)
if [ -z "$ssid_matched" ]; then
start_wg0
else
start_wg1
fi
done &
write_log "wg service exit ..."
附加影响
树莓派上部署了 homeassistant, jellyfin,smb 等服务,之前用手机访问这些服务。总是在外用公网地址,在家用内网地址,频繁切换服务器地址,重新登录。现在可以解放了。