本来我是将树莓派连接到路由器,从而在电脑端通过IP访问。远在局域网之外的队友怎么访问呢?
它的原理比较简单:
树莓派主动向某公网服务器建立ssh连接,并请求公网服务器开启一个额外的SSH的服务端口,充当树莓派的反向代理服务。树莓派与公网服务器之间的TCP(SSH)连接是树莓派主动发起的,而公网服务器与外部用户之间的TCP(SSH)连接是外部用户主动发起的,公网服务器在中间充当代理角色,转发两侧的数据。
从更具体的角度讲,外部用户到公网服务器之间可以建立多条TCP连接,而公网服务器到树莓派则只有一条共享的反向的TCP连接。
树莓派向公网服务器建立的ssh连接可能因为网络问题而断开,所以一般我们不直接使用ssh命令而是使用一个监督程序叫做autossh,它负责拉起ssh命令,并且当ssh断开后可以重新拉起ssh。
首先,因为autossh会帮我们建立到公网服务器的ssh连接,为了免去输入密码的问题,我们要让公网服务器信任树莓派。
pi@raspberrypi:~ $ ssh-keygen -t rsa
这通过ssh自带的命令就可以完成
pi@raspberrypi:~ $ ssh-copy-id -i ~/.ssh/id_rsa root@公网IP
上述命令将树莓派pi用户授信给公网服务器x.x.x.x的root用户,此后在pi用户下ssh root@ip 就不需要输入密码了,你可以自己验证。
pi@raspberrypi:~ $ sudo apt-get install autossh
#Insert the following scripts #!/bin/sh ### BEGIN INIT INFO # Provides: autossh # Required-Start: $local_fs $remote_fs $network $syslog # Required-Stop: $local_fs $remote_fs $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: starts the autossh # Description: starts the autossh ### END INIT INFO case "$1" in start) echo "start autossh" killall -0 autossh if [ $? -ne 0 ];then sudo /usr/bin/autossh -M 888 -fN -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" -o "PasswordAuthentication=no" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 2222:localhost:22 -i /home/pi/.ssh/id_rsa root@ip fi ;; stop) sudo killall autossh ;; restart) sudo killall autossh sudo /usr/bin/autossh -M 888 -fN -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" -o "PasswordAuthentication=no" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 2222:localhost:22 -i /home/pi/.ssh/id_rsa root@ip ;; *) echo "Usage: $0 (start|stop|restart)" ;; esac exit 0 #Then save the file
//记得换成自己VPS的登录名和IP
这个脚本支持 start/stop/restart 三个命令,启动autossh的命令参数作用如下:
本来打算将上述脚本做到开启自动启动中,但是试验发现开机没有成功启动autossh,索性把它写到crontab里算了:
执行 crontab -e,然后填入:
* * * * * /bin/bash /etc/init.d/autossh.sh start
//每隔一分钟执行一次
接下来,你可以观察是否有autossh进程被拉起:
ps aux|grep autossh root 1700 0.0 0.0 1868 64 ? Ss 06:23 0:00 /usr/lib/autossh/autossh -M 888 -N -o PubkeyAuthentication=yes -o StrictHostKeyChecking=false -o PasswordAuthentication=no -o ServerAliveInterval 60 -o ServerAliveCountMax 3 -R 2222:localhost:22 -i /home/pi/.ssh/id_rsa root@47.XX.XX.XX (打码了) pi 1709 0.0 0.0 7348 556 pts/2 S+ 06:23 0:00 grep --color=auto autossh
登入VPS,再执行如下命令:
ssh pi@localhost -p 2222
//pi用户默认的密码为 raspberry
参考连接:
1. https://yuerblog.cc/2017/09/14/raspberry-pi-autossh-reverse-tunnel/
2. http://blog.niuhemoon.xyz/pages/2018/09/04/Raspi_Remote_SSH_Tunnel/
原文:https://www.cnblogs.com/lfri/p/11830365.html