远程访问简介

有时,您需要在不连接显示器、键盘和鼠标的情况下访问树莓派。也许树莓派被嵌入到机器人中,或者安装在不方便操作的位置。又或者您手头没有多余的显示器。

局域网内的远程控制

要从局域网中的另一台设备远程控制您的树莓派,请使用以下服务之一:

SSH(Secure Shell)提供对树莓派终端会话的安全访问。VNC(虚拟网络计算)则提供对树莓派桌面屏幕共享的安全访问。您只需要另一台计算机、一个局域网,以及树莓派的本地IP 地址地址。Raspberry Pi Connect 可以安全地共享您的树莓派屏幕,无需事先确定其本地 IP 地址。

在局域网内实现设备间文件共享

像NFS(网络文件系统)、SCP(安全复制协议)、Samba以及rsync等服务,可以让您在局域网内的设备之间共享文件,而无需直接操控远程设备。当您需要从一台设备访问另一台设备上存储的数据时,这些服务非常有用。

通过互联网进行远程控制

要从任何连接互联网的设备远程控制您的树莓派,您可以:

查找树莓派的 IP 地址

大多数从其他机器连接树莓派的方法都需要您知道树莓派的本地 IP 地址。

任何连接到局域网的设备都会被分配一个 IP 地址。为了从另一台机器使用SSH 连接到您的 Raspberry Pi 设备。或VNC连接您的树莓派,您需要知道树莓派设备的 IP 地址。如果您有显示器连接,这很容易,而且有多种方法可以从网络上的另一台机器远程查找它。

要查找树莓派的本地 IP 地址,请使用以下方法之一。

桌面

将鼠标悬停在系统托盘中的网络图标上,会出现一个工具提示。该工具提示显示您当前连接的网络名称和您的 IP 地址。

the Network Manager tooltip displaying a Wi-Fi network name and IP address

命令行

运行以下命令将您的本地 IP 地址输出到命令行:

$ hostname -I

启动输出

如果您将显示器与树莓派配合使用并且启动到命令行而不是桌面,启动序列会在登录提示符之前的最后几条输出消息中包含您的 IP 地址。

,并使用 Network Manager 小部件来

您可以使用内置的 Network Manager CLI (nmcli) to access details about your network. Run the following command:

$ nmcli device show

您应该会看到类似如下的输出:

GENERAL.DEVICE:                         wlan0
GENERAL.TYPE:                           wifi
GENERAL.HWADDR:                         D0:3B:FF:41:AB:8A
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     exampleNetworkName
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/2
IP4.ADDRESS[1]:                         192.168.1.42/24
IP4.GATEWAY:                            192.168.1.1
IP4.ROUTE[1]:                           dst = 192.168.1.0/24, nh = 0.0.0.0, mt = 600
IP4.ROUTE[2]:                           dst = 0.0.0.0/0, nh = 192.168.1.1, mt = 600
IP4.DNS[1]:                             192.168.1.3
IP6.ADDRESS[1]:                         ab80::11ab:b1fc:bb7e:a8a5/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = ab80::/64, nh = ::, mt = 1024

GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
GENERAL.STATE:                          100 (connected (externally))
GENERAL.CONNECTION:                     lo
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/1
IP4.ADDRESS[1]:                         127.0.0.1/8
IP4.GATEWAY:                            --
IP6.ADDRESS[1]:                         ::1/128
IP6.GATEWAY:                            --

GENERAL.DEVICE:                         p2p-dev-wlan0
GENERAL.TYPE:                           wifi-p2p
GENERAL.HWADDR:                         (unknown)
GENERAL.MTU:                            0
GENERAL.STATE:                          30 (disconnected)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --

GENERAL.DEVICE:                         eth0
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         D0:3B:FF:41:AB:89
GENERAL.MTU:                            1500
GENERAL.STATE:                          20 (unavailable)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --
WIRED-PROPERTIES.CARRIER:               off
IP4.GATEWAY:                            --
IP6.GATEWAY:                            --

此命令输出有关树莓派上可用的各种网络接口的信息。检查GENERAL.TYPE row to see which kind of network interface each block describes. For example, "ethernet" is the Ethernet port on your device, and "wifi" refers to the Wi-Fi chip built into some devices. You’ll look at different blocks of output to find your IP address depending on the way your device accesses the internet:

  • 如果您的设备使用 Wi-Fi 连接到互联网,请检查 "wifi" 块

  • 如果您的设备使用以太网端口连接到互联网,请检查 "ethernet" 块

当您识别出正确的网络接口块时,查找名为IP4.ADDRESS[1] for an IPv4 address or IP6.ADDRESS[1] for an IPv6 address. You can ignore the trailing slash and number (for example, /24) in those fields.

在上面的示例中,树莓派使用 Wi-Fi 访问互联网。请检查GENERAL.TYPE field reads "wifi" to find the IP address. In this case, you can access this device using the IPv4 address in the IP4.ADDRESS[1] field: 192.168.1.42.

解析raspberrypi.local with mDNS

树莓派 OS 支持作为 Avahi 服务一部分的多播 DNS。

如果您的设备支持 mDNS,您可以使用其主机名和.local suffix. The default hostname on a fresh Raspberry Pi OS install is raspberrypi, so by default any Raspberry Pi running Raspberry Pi OS responds to:

$ ping raspberrypi.local

如果可以访问树莓派,ping will show its IP address:

PING raspberrypi.local (192.168.1.131): 56 data bytes
64 bytes from 192.168.1.131: icmp_seq=0 ttl=255 time=2.618 ms
如果您使用控制中心更改树莓派的系统主机名,raspi-config, or /etc/hostname, Avahi updates the .local mDNS address. If you don’t remember the hostname of your Raspberry Pi, you can install Avahi on another device, then use avahi-browse浏览本地网络上的所有主机和服务。

检查路由器的设备列表

在 Web 浏览器中,导航到路由器的 IP 地址。然后,使用您的凭证登录。

您路由器的 IP 地址通常是http://192.168.1.1, but not always. You might find your router’s address and credentials printed on a label on your router.

这将带您进入控制面板。浏览到已连接设备列表或类似选项(所有路由器都不同),您应该会看到一些您认识的设备。某些设备会被识别为 PC、平板电脑、手机、打印机等,因此您应该认识其中一些并排除它们,从而确定哪个是您的 Raspberry Pi。

如果您通过网线将 Raspberry Pi 连接到网络,请尝试在列表中筛选有线设备。这样可供选择的设备会更少。

查找设备,使用nmap

网络映射器命令 (nmap) is a free and open source tool for network discovery. It is available for Linux, macOS, and Windows.

  • 要安装在Linux,安装nmap package, for example, apt install nmap.

  • 要安装在macOS或如果你打开一个窗口,就会发现窗口边框的设计已经发生了显著变化。旧式的窗口设计相较于苹果和微软如今推出的版本,总显得有些过时,因此我十分期待对其进行升级。现在的窗口在角落处采用了柔和的弧线设计,标题栏也更加简洁,新增了关闭、最小化和最大化按钮,并且边框也变得薄了许多。过去窗口边框较厚的原因之一,正是为了让调整大小的抓手足够大,以便用鼠标轻松找到。为了避免这个问题,现在的抓手略微延伸出窗口之外;当你将鼠标指针悬停在有焦点的窗口外侧时,鼠标指针会自动切换,以显示抓手的轮廓。,请参阅nmap.org 下载页面.

要使用nmap to scan the devices on your network, you need to know the subnet you are connected to. First, find the local IP address of the computer you’re using:

  • OnLinux,输入hostname -I into a terminal window

  • OnmacOS,转到系统设置 > 网络,选择您的活动网络连接,然后点击详细信息…button

  • On如果你打开一个窗口,就会发现窗口边框的设计已经发生了显著变化。旧式的窗口设计相较于苹果和微软如今推出的版本,总显得有些过时,因此我十分期待对其进行升级。现在的窗口在角落处采用了柔和的弧线设计,标题栏也更加简洁,新增了关闭、最小化和最大化按钮,并且边框也变得薄了许多。过去窗口边框较厚的原因之一,正是为了让调整大小的抓手足够大,以便用鼠标轻松找到。为了避免这个问题,现在的抓手略微延伸出窗口之外;当你将鼠标指针悬停在有焦点的窗口外侧时,鼠标指针会自动切换,以显示抓手的轮廓。,转到控制面板,然后在网络和共享中心旁边,点击查看网络连接下,选择您的活动网络连接并点击查看此连接的状态

接下来,扫描整个子网以查找其他设备。大多数本地网络使用 IPv4,它使用四个数字,每个 IP 地址的数字值介于 1 到 255 之间。您子网上的设备都使用相同的前三个数字。例如,如果您的 IP 地址是192.168.1.5, other devices will use addresses like 192.168.1.2, 192.168.1.6 and 192.168.1.200. To scan this subnet with nmap, pass the string 192.168.1.0/24, which covers the subnet range 192.168.1.0 to 192.168.1.255. Use the -sn flag to run a ping 扫描在整个子网范围内:

$ sudo nmap -sn 192.168.1.0/24
这可能需要长达一分钟的时间,取决于您的本地网络速度。

Ping 扫描会查询范围内的所有 IP 地址以获取响应。对于每个响应 ping 的设备,输出会显示主机名和 IP 地址,如下所示:

Starting Nmap 6.40 ( http://nmap.org ) at 2014-03-10 12:46 GMT
Nmap scan report for hpprinter (192.168.1.2)
Host is up (0.00044s latency).
Nmap scan report for Gordons-MBP (192.168.1.4)
Host is up (0.0010s latency).
Nmap scan report for ubuntu (192.168.1.5)
Host is up (0.0010s latency).
Nmap scan report for raspberrypi (192.168.1.8)
Host is up (0.0030s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.41 seconds

上面的输出显示了一个主机名为raspberrypi has IP address 192.168.1.8.

使用智能手机应用程序查找设备

Fing 应用程序是一款适用于智能手机的免费网络扫描器。它适用于安卓和好文章,我们永远无法满足于寻址RGB事物 :D.

  1. 将您的手机连接到与 Raspberry Pi 相同的网络。

  2. 打开 Fing 应用程序后,点击屏幕右上角的刷新按钮。

  3. 几秒钟后,您应该会看到已连接到网络的所有设备列表。

  4. 向下滚动到制造商为"Raspberry Pi"的项目。IP 地址显示在左下角,MAC 地址显示在项目的右下角。

使用 SSH 访问远程终端

您可以通过S安全SSH协议,从同一网络中的另一台计算机远程访问树莓派的终端。

启用 SSH 服务端

默认情况下,Raspberry Pi OS 会禁用 SSH 服务端。您可以通过以下方式之一启用 SSH:

在桌面环境中
  1. 根据偏好设置菜单中,启动控制中心.

  2. 导航到接口选项卡。

  3. 选择启用在SSH 连接到您的 Raspberry Pi 设备。.

  4. 点击确定.

在刷写全新操作系统镜像时

要在全新安装的 Raspberry Pi OS 上配置 SSH:

  1. 请按照使用 Imager 进行安装指南中找到完整的操作说明。

  2. 在自定义 > 远程访问选项卡中的说明操作,将启用SSH开关切换至启用状态。

  3. 选择使用密码认证即可使用与您在本地使用树莓派时相同的用户名和密码登录。选择使用公钥认证到配置 SSH 密钥以通过基于密钥的身份验证进行登录。

从终端
  1. 输入sudo raspi-config in a terminal window.

  2. 选择Interfacing Options.

  3. 导航到并选择SSH.

  4. 选择Yes.

  5. 选择Ok.

  6. 选择Finish.

手动
  1. 创建一个名为ssh in the boot partition:

    $ sudo touch /boot/firmware/ssh
  2. 重启设备:

    $ sudo reboot

连接到 SSH 服务器

在您的计算机上打开一个终端窗口,并输入以下命令,将<ip address> placeholder with the 替换为您要连接的树莓派的 IP 地址。和<username> with your username:

$ ssh <username>@<ip address>

当连接成功时,您将看到一条安全警告。请输入yes to continue. You will only see this warning the first time you connect.

根据提示输入您的账户密码。

现在您将看到树莓派的命令行提示符:

<username>@<hostname> ~ $

您现已通过远程方式连接到树莓派,可以执行命令了。

[3] 树莓派的IP地址connection timed out error, you might have entered the wrong IP address for the Raspberry Pi. Check the 树莓派的IP地址.

通过SSH转发X11

在macOS和Windows系统上,您必须安装第三方X服务器才能使用X11转发功能。

X11允许通过SSH运行图形化应用程序。传递-Y flag to forward an X session over SSH:

$ ssh -Y <username>@<ip address>

认证成功后,您将看到与平时相同的命令行界面。此外,您还可以打开由X服务器渲染的图形窗口。例如,输入以下命令以启动一个Geany窗口:

$ geany &

配置免密码 SSH

若要在每次连接时无需输入密码即可远程访问您的树莓派,请使用SSH密钥对。

使用Raspberry Pi Imager预配置操作系统镜像

在使用Raspberry Pi Imager配置操作系统镜像时,您可以预先设置SSH密钥,以便使用运行Imager的计算机上已有的密钥。

  1. 请按照使用Imager进行安装的指南来配置您的启动镜像。

  2. 在远程访问选项卡中的说明操作,将启用SSH开关切换至启用状态。

  3. 选择使用公钥认证.

    • 如果您已经拥有存储在~/.ssh/id_rsa.pub, Imager automatically uses that public key to prefill the text box.

    • 中的SSH公钥,否则请浏览至您的公钥所在位置。

  4. 选择下一步以继续镜像制作过程。

手动配置SSH密钥

如果您已经安装了Raspberry Pi OS,可以更新现有配置以启用SSH密钥认证。

检查是否存在现有的SSH公钥

要检查用于远程连接树莓派的计算机上是否已有SSH公钥,请运行以下命令:

$ ls ~/.ssh

如果您看到名为id_ed25519.pub, id_rsa.pub, or id_dsa.pub, you already have an SSH key. Skip SSH keypair generation and proceed to 将该SSH密钥添加到您的SSH身份列表中.

生成新的SSH密钥对

本指南提供了生成新 RSA 密钥的说明。为了提高安全性,您也可以生成一个Ed25519密钥。输入-t ed25519 to ssh-keygen and replace rsa with ed25519 when referencing your public and private key file names to use an Ed25519 key.

要生成新的 SSH 密钥对,请输入以下命令:

$ ssh-keygen

当系统提示保存密钥的位置时,按输入键以使用默认位置,~/.ssh/id_rsa.

当系统提示输入可选的密钥口令时,按输入键以不设置密钥口令。

运行以下命令以查看.ssh directory:

$ ls ~/.ssh

您应该会看到文件id_rsa and id_rsa.pub:

authorized_keys  id_rsa  id_rsa.pub  known_hosts

该id_rsa file contains your private key. Keep this secure on the computer you use to remotely connect to the Raspberry Pi.

该id_rsa.pub file contains your public key. You will share this key with your Raspberry Pi. When you connect with the Raspberry Pi remotely, it will use this key to verify your identity.

将 SSH 密钥添加到您的 SSH 身份列表中

启动 SSH 代理:

$ eval "$(ssh-agent -s)"

接下来,将您的密钥身份添加到ssh-agent with the following command:

$ ssh-add ~/.ssh/id_rsa

将公钥复制到您的 Raspberry Pi 上

在用于远程连接 Raspberry Pi 的计算机上,使用以下命令将您的公钥安全地复制到 Raspberry Pi:

$ ssh-copy-id <username>@<ip address>

系统提示时,请输入您在 Raspberry Pi 上的用户账户密码。 现在您可以无需输入密码即可连接到您的 Raspberry Pi。

手动将公钥复制到您的 Raspberry Pi 上

如果您的操作系统不支持ssh-copy-id, you can instead copy your public key with scp.

首先,在您的 Raspberry Pi 上,请创建 Linux 预期查找密钥的目录:

$ mkdir .ssh

然后,为.ssh directory:

$ chmod 700 .ssh

在您的常用计算机上,使用scp to copy your public key to a file named .ssh/authorized_keys on your Raspberry Pi:

$ scp .ssh/id_rsa.pub <username>@<ip address>:.ssh/authorized_keys
上述命令假定您此前从未授权任何密钥访问您的 Raspberry Pi。如果您之前已添加过至少一个密钥,则应在authorized_keys file to preserve your existing keys.

的末尾添加一行包含公钥的内容。 当系统提示时,请输入您在 Raspberry Pi 上的用户账户密码。

然后,在您的 Raspberry Pi 上,配置相关权限。authorized_keys file:

$ chmod 644 .ssh/authorized_keys

现在,您可以无需输入密码即可连接到您的树莓派。

限制可连接的用户

如果您希望限制特定用户账户的SSH访问权限,请编辑SSH服务器的配置文件:

$ sudo nano /etc/ssh/sshd_config

定位到AllowUsers directive and add the usernames you want to permit. If the line doesn’t exist, add it to the bottom of the file:

AllowUsers alice bob

您也可以使用DenyUsers to explicitly stop specific usernames from signing in:

DenyUsers jane john

保存文件并重启SSH服务以使更改生效:

$ sudo systemctl restart ssh

使用VNC进行屏幕共享

有时,直接操作设备并不方便。虚拟网络计算(VNC)允许您从另一台设备上控制目标设备的桌面。

VNC依赖于客户端和服务器端。客户端运行在您可以直接操作的设备上,例如个人笔记本电脑、台式机、平板电脑或手机;而服务器端则运行在您的树莓派上。使用VNC时,客户端会将键盘和鼠标事件发送给服务器端,服务器端会在树莓派上执行这些操作,并将屏幕更新返回给客户端。

VNC客户端会在一个窗口中显示树莓派的桌面,您可以像在树莓派本机上一样与该桌面进行交互。

Raspberry Pi OS 包含wayvnc。它提供了一个可在设备设置中启用的VNC服务器。

在树莓派上使用VNC之前,您必须先启用VNC服务器。

启用VNC服务器

树莓派操作系统既支持通过图形界面,也支持通过命令行来启用VNC服务器。

当启用后,您可以在以下路径访问WayVNC的配置:/etc/wayvnc/.

通过图形界面启用VNC服务器

  1. 启动树莓派的图形化桌面。

  2. 在桌面的任务栏中选择树莓派图标。

  3. 选择偏好设置 > 控制中心。

    Select Control Centre from the Preferences menu in the system tray
  4. 导航到接口选项卡。

  5. 将“VNC”旁边的单选按钮切换至“启用”状态。

    In the Interfaces tab, click the VNC toggle into the active position to enable VNC.
  6. 选择确定单击“应用”按钮以保存配置更改。

通过命令行启用VNC服务器

使用raspi-config命令可用于在命令行中启用VNC服务器。

  1. 打开raspi-config with the following line:

    $ sudo raspi-config
  2. 导航至接口选项. 按下Enter to select.

  3. 选择VNC. 按下Enter to select.

  4. 在您是否希望启用 VNC 服务器?,突出显示<Yes> and press Enter.

  5. 按下Enter to return to the menu. Press Esc to exit raspi-config.

连接到 VNC 服务器

要连接到您的树莓派,您需要以下内容:

  • 您的树莓派与运行VNC客户端的设备连接到同一网络(例如,家庭无线网络或VPN)。

  • 您的树莓派的主机名或 IP 地址

  • 树莓派上某个账户的有效用户名和密码组合

如果您不知道设备的IP地址,请参阅我们关于查找您的IP地址的说明.

  1. 下载老虎VNC您可以从以下位置安装最新版本:其 GitHub 仓库的发布页面点击最新版本中的链接,找到适用于您平台的二进制文件。Windows 用户应下载一个exe; macOS users should download the dmg; Linux users should install the jar.

  2. 在您的客户端设备上,启动 TigerVNC。在 macOS 和 Windows 上,您可以双击可执行文件。在 Linux 上,请先安装 Java。sudo apt install default-jre, then run java -jar VncViewer-<version>.jar, replacing the <version> placeholder with the version you downloaded.

  3. 在“VNC服务器”字段中,输入您的树莓派的IP地址。

    Entering the Raspberry Pi device’s local IP address into TigerVNC
  4. 单击“选项”按钮。转到“输入”选项卡。选中“无光标时显示点”复选框,以确保在 TigerVNC 中始终能够看到光标。

    TigerVNC option to render the cursor at all times as a dot
  5. 单击“连接”按钮以启动与服务器的连接。

    • 如果 TigerVNC 提示“主机名与服务器证书不匹配”,请单击“是”按钮以继续。

      TigerVNC warning about mismatched certificates"
    • 如果 TigerVNC 提示“证书由未知机构签名”,请单击“是”按钮,为您的 Raspberry Pi 添加例外。

      TigerVNC warning about certificates signed by an unknown authority
  6. 当系统提示输入用户名和密码时,请输入您的凭据。

    Entering a username and password to authenticate through TigerVNC
  7. 单击“确定”按钮以向 VNC 服务器进行身份验证。如果您的凭据正确,TigerVNC 应会打开一个窗口,其中显示与您在 Raspberry Pi 上的账户相对应的桌面。您应该能够使用鼠标和键盘与桌面交互并输入文本。

    The desktop of a Raspberry Pi after successfully authenticating with TigerVNC

使用 Raspberry Pi Connect 进行远程访问

您可以使用 Raspberry Pi Connect,通过另一台设备上的浏览器远程访问 Raspberry Pi。Connect 会自动处理配置,因此您无需查找 Raspberry Pi 设备的本地 IP 地址、网络的公网 IP 地址,也无需修改本地网络的防火墙设置即可实现外部访问。

Connect 提供在运行 Wayland 窗口服务器的树莓派机型上进行屏幕共享的功能,并支持在所有树莓派机型上实现远程 Shell(终端)访问。

了解更多信息,请参阅Connect 的文档.

使用 SCP 共享文件

安全复制协议(scp) sends files over SSH. You can use scp to copy files between your Raspberry Pi and another computer.

将文件复制到您的 Raspberry Pi

要复制名为myfile.txt from your personal computer to a user’s home folder on your Raspberry Pi, run the following command from the directory containing myfile.txt, replacing the <username> placeholder with the username you use to log in to your Raspberry Pi and the <pi_ip_address> placeholder with your Raspberry Pi device’s IP address:

$ scp myfile.txt <username>@<pi_ip_address>:

要将文件复制到特定目录,请在: in the scp command. Create the folder before you run scp, since scp won’t create folders automatically. For instance, the following command copies a file named myfile.txt into the project/ directory within a user’s home folder:

$ scp myfile.txt <username>@<pi_ip_address>:project/

从您的 Raspberry Pi 复制文件

要复制名为myfile.txt from a user’s home directory on a Raspberry Pi to the current directory on another computer, run the following command:

$ scp <username>@<pi_ip_address>:myfile.txt .

使用一条命令复制多个文件

要复制多个文件,请在单条命令中列出文件名,并用空格分隔:

$ scp myfile.txt myfile2.txt <username>@<pi_ip_address>:

或者,使用通配符复制匹配特定过滤条件的所有文件。以下命令将复制所有以.txt:

$ scp *.txt <username>@<pi_ip_address>:

以下命令将复制所有以m:

$ scp m* <username>@<pi_ip_address>:

以下命令将复制所有以m and end with .txt:

$ scp m*.txt <username>@<pi_ip_address>:

要复制名称中包含空格的文件,请将文件名用引号括起来:

$ scp "my file.txt" <username>@<pi_ip_address>:

复制文件夹

要复制文件夹及其所有内容,请将文件夹名与-r (recursive) flag:

$ scp -r project/ <username>@<pi_ip_address>:

使用 在计算机之间同步文件夹rsync

您可以使用rsync to synchronise folders between computers. For example, you can use rsync to transfer new pictures taken by your Raspberry Pi to your personal computer automatically.

在您能够配置 之前rsync, determine values for the following:

  • <pi_ip_address>: your Raspberry Pi device’s local IP address. For more information, see 查找您的 Raspberry Pi 设备的 IP 地址.

  • <pi_username>: the username you use to log into your Raspberry Pi

  • <pi_folder_name>: the name of the folder you want to copy files from on your Raspberry Pi

  • <pc_folder_name>: the name of the folder you want to synchronise on your personal computer

要配置rsync to synchronise files, complete the following steps on your personal computer, replacing placeholders in the commands with the values you determined above:

  1. 创建您想要同步的文件夹:

    $ mkdir <pc_folder_name>
  2. 使用 将文件同步到该文件夹rsync:

    $ rsync -avz -e ssh <pi_username>@<pi_ip_address>:<pi_folder_name>/ <pc_folder_name>/

此命令会将 Raspberry Pi 上选定文件夹中的所有文件复制到个人电脑上的选定文件夹中。如果您多次运行该命令,rsync keeps track of the files you have already downloaded and skips them. If you delete or modify an already synchronised file on the Raspberry Pi, rsync updates the files on your personal computer accordingly.

网络文件系统(NFS)

网络文件系统(NFS)允许您与同一网络上的其他计算机或设备共享位于某一联网计算机上的目录。存放该目录的计算机称为服务器,连接到该服务器的计算机或设备称为客户端。客户端通常mount the shared directory to make it a part of their own directory structure. The shared directory is an example of a shared resource or network share.

NFS 是在 Linux/Unix 环境中创建简单 NAS(网络附加存储)的常用方式。

NFS 可能最适合永久网络挂载的目录,例如/home directories or regularly-accessed shared resources. If you want a network share that guest users can easily connect to, Samba is better suited to the task. Tools to temporarily mount and detach from Samba shares are more readily available across operating systems.

部署 NFS 之前,您必须熟悉:

  • Linux 文件和目录权限

  • 文件系统的挂载和卸载

设置基本的 NFS 服务器

使用以下命令安装所需的软件包:

$ sudo apt install nfs-kernel-server

为了便于维护,我们将把所有 NFS 导出隔离在一个目录中,真实的目录将通过--bind option.

假设我们要导出用户的主目录,这些目录位于/home/users. First we create the export filesystem:

$ sudo mkdir -p /export/users
如果您计划配置 LDAP/NIS 身份验证,请跳过chmod step below.

授予/export and /export/users read, write, and execute permissions (777) so you can access the NFS share from the client without LDAP/NIS authentication:

$ chmod -R 777 /export

接下来,挂载真实的users directory with:

$ sudo mount --bind /home/users /export/users

为了避免每次重启后重新输入,我们在/etc/fstab:

/home/users    /export/users   none    bind  0  0

与 NFS 服务器相关的配置文件有三个:

  1. /etc/default/nfs-kernel-server

  2. /etc/default/nfs-common

  3. /etc/exports

中唯一重要的选项是/etc/default/nfs-kernel-server for now is NEED_SVCGSSD. It is set to "no" by default, which is fine, because we are not activating NFSv4 security this time.

为了自动映射 ID 名称,文件/etc/idmapd.conf must exist on both the client and the server with the same contents and with the correct domain names. Furthermore, this file should have the following lines in the Mapping section:

[Mapping]

Nobody-User = nobody
Nobody-Group = nogroup

但是,请注意客户端可能对 Nobody-User 和 Nobody-Group 有不同的要求。例如,在 RedHat 变体上,它是nfsnobody for both. If you’re not sure, use the following commands to check whether nobody and nogroup are there:

$ cat /etc/passwd
$ cat /etc/group

这样,服务器和客户端就不需要用户共享相同的 UID/GUID。对于使用基于 LDAP 身份验证的用户,请在idmapd.conf of your clients:

[Translation]

Method = nsswitch

这将导致idmapd to know to look at nsswitch.conf to determine where it should look for credential information. If you have LDAP authentication already working, nsswitch shouldn’t require further explanation.

将我们的目录导出到本地网络192.168.1.0/24, add the following two lines to /etc/exports:

/export       192.168.1.0/24(rw,fsid=0,insecure,no_subtree_check,async)
/export/users 192.168.1.0/24(rw,nohide,insecure,no_subtree_check,async)

端口映射锁定(可选)

NFS 上的文件对网络上的任何人都是开放的。作为一项安全措施,您可以限制对指定客户端的访问。

将以下行添加到/etc/hosts.deny:

rpcbind mountd nfsd statd lockd rquotad : ALL

首先阻止所有客户端,只有在/etc/hosts.allow (added below) will be allowed to access the server.

现在将以下行添加到/etc/hosts.allow:

rpcbind mountd nfsd statd lockd rquotad : <list of IPv4s>

现在,每当检测到车轮时,系统会计算螺母的数量。如果该数量低于目标值,则会向 Azure IoT Hub 发送一条消息。<list of IPv4s> is a list of the IP addresses of the server and all clients. (These have to be IP addresses because of a limitation in rpcbind, which doesn’t like hostnames.) Note that if you have NIS set up, you can just add these to the same line.

确保授权IP地址列表包括localhost address (127.0.0.1), as the startup scripts in recent versions of Ubuntu use the rpcinfo command to discover NFSv3 support, and this will be disabled if localhost is unable to connect.

最后,要使更改生效,请重启服务:

$ sudo systemctl restart nfs-kernel-server

配置NFS客户端

现在服务器已运行,您需要设置任何可以访问它的客户端。首先,安装所需的软件包:

$ sudo apt install nfs-common

在客户端上,我们可以使用一个命令挂载完整的导出树:

$ mount -t nfs -o proto=tcp,port=2049 <nfs-server-IP>:/ /mnt

您也可以指定NFS服务器主机名而不是其IP地址,但在这种情况下,您需要确保主机名可以在客户端侧解析为IP。确保始终可以解析的可靠方法是使用/etc/hosts file.

请注意<nfs-server-IP>:/export is not necessary in NFSv4, as it was in NFSv3. The root export :/ defaults to export with fsid=0.

我们也可以使用以下命令挂载导出的子目录:

$ mount -t nfs -o proto=tcp,port=2049 <nfs-server-IP>:/users /home/users

为确保每次重启时都挂载,请将以下行添加到/etc/fstab:

<nfs-server-IP>:/   /mnt   nfs    auto  0  0

如果挂载后/proc/mounts appears as <nfs-server-IP>:// (with two slashes), then you might need to specify two slashes in /etc/fstab, or else umount might complain that it cannot find the mount.

端口映射锁定(可选)

将以下行添加到/etc/hosts.deny:

rpcbind : ALL

首先阻止所有客户端,只有在/etc/hosts.allow (added below) will be allowed to access the server.

现在将以下行添加到/etc/hosts.allow:

rpcbind : <NFS server IP address>

现在,每当检测到车轮时,系统会计算螺母的数量。如果该数量低于目标值,则会向 Azure IoT Hub 发送一条消息。<NFS server IP address> is the IP address of the server.

配置复杂的NFS服务器

NFS用户权限基于用户ID(UID)。客户端上任何用户的UID必须与服务器上的UID匹配,用户才能获得访问权限。常用的方法有:

  • 手动密码文件同步

  • 使用LDAP

  • 使用DNS

  • 使用NIS

请注意,在主要用户具有root访问权限的系统上必须小心:该用户可以更改系统上的UID以允许自己访问任何人的文件。本页面假设管理团队是唯一拥有root访问权限的团队,并且都是可信的。任何其他情况都代表更高级的配置,此处不予讨论。

组权限

用户的文件访问权限由其在客户端上的组成员资格决定,而不是在服务器上。但有一个重要限制:从客户端传递到服务器的最大组数为16个,如果用户在客户端上属于16个以上的组,某些文件或目录可能会意外无法访问。

DNS(仅在使用DNS时可选)

将任何客户端名称和IP地址添加到/etc/hosts. (The IP address of the server should already be there.) This ensures that NFS will still work even if DNS goes down. Alternatively you can rely on DNS if you want – it’s up to you.

NIS(仅在使用NIS时可选)

这适用于使用NIS的客户端。否则您不能使用netgroups,应该在以下位置指定各 IP 或主机名:/etc/exports. Read the BUGS section in man netgroup for more information.

首先,编辑/etc/netgroup and add a line to classify your clients (this step is not necessary, but is for convenience):

myclients (client1,,) (client2,,) ...

现在,每当检测到车轮时,系统会计算螺母的数量。如果该数量低于目标值,则会向 Azure IoT Hub 发送一条消息。myclients is the netgroup name.

接下来运行以下命令重建NIS数据库:

$ sudo make -C /var/yp

文件名yp refers to Yellow Pages, the former name of NIS.

端口映射锁定(可选)

将以下行添加到/etc/hosts.deny:

rpcbind mountd nfsd statd lockd rquotad : ALL

首先阻止所有客户端,只有在/etc/hosts.allow (added below) will be allowed to access the server.

考虑添加以下行到/etc/hosts.allow:

rpcbind mountd nfsd statd lockd rquotad : <list of IPs>

现在,每当检测到车轮时,系统会计算螺母的数量。如果该数量低于目标值,则会向 Azure IoT Hub 发送一条消息。<list of IPs> is a list of the IP addresses of the server and all clients. These have to be IP addresses because of a limitation in rpcbind. Note that if you have NIS set up, you can just add these to the same line.

软件包安装和配置

安装必要的软件包:

$ sudo apt install rpcbind nfs-kernel-server

编辑/etc/exports and add the shares:

/home @myclients(rw,sync,no_subtree_check)
/usr/local @myclients(rw,sync,no_subtree_check)

上面的示例共享/home and /usr/local to all clients in the myclients netgroup.

/home 192.168.0.10(rw,sync,no_subtree_check) 192.168.0.11(rw,sync,no_subtree_check)
/usr/local 192.168.0.10(rw,sync,no_subtree_check) 192.168.0.11(rw,sync,no_subtree_check)

上面的示例共享/home and /usr/local to two clients with static IP addresses. If you want instead to allow access to all clients in the private network falling within a designated IP address range, consider the following:

/home 192.168.0.0/255.255.255.0(rw,sync,no_subtree_check)
/usr/local 192.168.0.0/255.255.255.0(rw,sync,no_subtree_check)

在这里,rw makes the share read/write, and sync requires the server to only reply to requests after any changes have been flushed to disk. This is the safest option; async is faster, but dangerous. It is strongly recommended that you read man exports if you are considering other options.

设置完成后/etc/exports, export the shares:

$ sudo exportfs -ra

每当需要运行此命令时/etc/exports is modified.

重启服务

重启rpcbind and NFS for the changes to take effect:

$ sudo systemctl restart rpcbind
$ sudo systemctl restart nfs-kernel-server

需要考虑的安全事项

除了上面讨论的UID问题外,还应该注意,攻击者可能会伪装成允许映射共享的机器,从而可以创建任意UID来访问您的文件。解决这个问题的一种方法是IPSec。您可以设置所有域成员只能通过IPSec进行通信,这将有效地验证您的客户端身份。

IPSec的工作原理是使用服务器的公钥加密发送到服务器的流量,服务器发回的所有回复都使用客户端的公钥加密。流量使用相应的私钥进行解密。如果客户端没有应该拥有的密钥,它就无法发送或接收数据。

IPSec的替代方案是物理隔离网络。这需要单独的网络交换机和单独的以太网卡,并确保该网络的物理安全。

故障排除

在加密的主目录内挂载NFS共享只会在您成功登录并解密主目录后才能工作。这意味着使用/etc/fstab在启动时挂载NFS共享将无法工作,因为在挂载时您的主目录尚未解密。使用符号链接有一个简单的解决方法:

  1. 创建一个替代目录来挂载NFS共享:

$ sudo mkdir /nfs
$ sudo mkdir /nfs/music
  1. 编辑/etc/fstab to mount the NFS share into that directory instead:

nfsServer:music    /nfs/music    nfs    auto    0 0
  1. 在您的主目录内创建指向实际挂载位置的符号链接。例如,在这种情况下删除以下内容:Music directory already existing there first:

$ rmdir /home/user/Music
$ ln -s /nfs/music/ /home/user/Music

Samba(SMB/CIFS)

Samba 是服务器消息块(SMB)网络协议的一个自由软件重新实现。使用 Samba,你可以在 Windows、macOS 和 Linux 设备之间共享文件夹。

在你的树莓派上安装 Samba

默认情况下,树莓派操作系统(Raspberry Pi OS)不包含 Samba。要在你的树莓派上安装 Samba,请运行以下命令,该命令会安装运行 Samba 服务器或客户端所需的所有依赖项:

$ sudo apt update
$ sudo apt install samba samba-common-bin smbclient cifs-utils

挂载来自 Windows 的共享文件夹

首先,你需要在你的 Windows 设备上共享一个文件夹。

启用共享功能

  1. 右键单击系统托盘,然后从菜单中选择网络和共享中心。

  2. 选择更改高级共享设置.

  3. 选择启用网络发现.

  4. 选择启用文件和打印机共享.

  5. 单击保存按钮以保存你的更改。

共享文件夹

按照以下步骤从 Windows 共享文件夹:

  1. 右键单击要共享的文件夹,然后选择属性.

  2. 选择分享选项卡。

  3. 单击高级共享按钮。

  4. 选择共享此文件夹;默认情况下,Windows 使用文件夹名称作为共享名称。

  5. 单击权限按钮。

  6. 配置每个人和完全控制权限。

  7. 单击确定按钮以退出权限页面。

  8. 单击确定按钮再次以退出高级共享页面。

  9. 选择安全选项卡。

  10. 配置每个人和完全控制权限。

  11. 单击确定按钮。

文件夹现在应该已共享。您可以通过更改权限和安全页面上的说明,为你的学校注册本项目。

Windows 10 共享向导

在 Windows 10 中有一个共享向导,可帮助完成其中一些步骤。

  1. 运行计算机管理应用程序,从开始栏中启动。

  2. 选择共享文件夹 > 共享.

  3. 右键单击并选择新建共享以启动共享向导。

  4. 单击下一步按钮。

  5. 选择要共享的文件夹,然后单击下一步按钮。

  6. 点击下一步使用共享默认设置,或选择自定义并设置所需的权限。

  7. 单击确定按钮。

  8. 单击完成按钮以共享该文件夹。

在 Raspberry Pi 上挂载文件夹

挂载在 Linux 中是指将一个文件夹附加到某个位置的过程,因此我们首先需要这个位置。

$ mkdir windowshare

现在,我们需要将远程文件夹挂载到该位置。远程文件夹是 Windows PC 的主机名或 IP 地址,以及共享时使用的共享名称。我们还需要提供用于访问远程机器的 Windows 用户名。别忘了替换<username> placeholder with your Raspberry Pi OS username.

$ sudo mount.cifs //<hostname or IP address>/<shared windows folder> /home/<username>/windowshare -o user=<name>

现在你应该能够在树莓派上查看 Windows 共享的内容。

$ ls windowshare/

“主机已关闭”错误

当 SMB 协议版本不匹配时会出现此错误,Linux Samba 客户端会返回一个误导性的错误消息。默认情况下,树莓派操作系统使用 2.1 及以上版本,与 Windows 7 及更高版本兼容。较旧的设备(包括某些 NAS 设备)可能需要使用 1.0 版本。要解决此错误,请添加一个版本条目(例如,,vers=1.0) to your mount command:

$ sudo mount.cifs //IP/share /mnt/point -o user=<uname>,vers=1.0

你可能需要尝试不同的版本以匹配服务器的版本。可能的值包括:

版本 说明

1.0

经典 CIFS/SMBv1 协议

2.0

SMBv2.002 协议。Windows Vista Service Pack 1 和 Windows Server 2008

2.1

SMBv2.1 协议。Microsoft Windows 7 和 Windows Server 2008R2

3.0

SMBv3.0 协议。Microsoft Windows 8 和 Windows Server 2012

3.02

SMBv3.0.2 协议。Microsoft Windows 8.1 和 Windows Server 2012R2

3.11

SMBv3.1.1 协议。Microsoft Windows 10 和 Windows Server 2016

3

SMBv3.0 及以上协议版本

从你的树莓派共享文件夹

首先,创建一个要共享的文件夹。此示例创建一个名为shared in the home folder of the current user:

$ cd ~
$ mkdir shared
$ chmod 0740 shared

现在我们需要告诉 Samba 在访问该文件夹时使用你的默认用户账户。当提示输入密码时,请输入你的密码,并替换<username> placeholder with the username of your primary user account:

$ sudo smbpasswd -a <username>

现在我们需要通过 Samba 配置文件告知 Samba 共享此文件夹。

sudo nano /etc/samba/smb.conf

在文件末尾添加以下内容以共享文件夹,并赋予远程用户读写权限。替换<username> placeholder with the username of the primary user account on your Raspberry Pi:

[share]
    path = /home/<username>/shared
    read only = no
    public = yes
    writable = yes

在同一文件中,找到workgroup line, and if necessary, change it to the name of the workgroup of your local Windows network.

workgroup = <your workgroup name here>

现在共享文件夹应出现在网络中的 Windows 或 macOS 设备上。输入你的树莓派用户名和密码以挂载该文件夹。

设置 Apache 网络服务器

Apache 是一种流行的网络服务器应用程序,可安装在树莓派上,使其能够提供网页服务。

Apache 本身可以通过 HTTP 提供 HTML 文件,通过添加额外模块后,还可以使用 PHP 等脚本语言提供动态网页。

要设置 Apache 网络服务器,请参阅官方 Apache 文档:https://httpd.apache.org/docs/.

通过网络启动你的树莓派

你可以设置一个 DHCP/TFTP 服务器,从而允许你从网络启动树莓派 3 或更新型号。

本说明假设你已有一个现有的家庭网络,并希望使用一台树莓派作为服务器. 你还需额外准备一台树莓派 3 或 4 作为客户端来进行启动。只需要一张 SD 卡,因为在完成初始客户端配置后,客户端将从服务器启动。

由于市面上网络设备和路由器种类繁多,我们无法保证网络启动能在所有设备上正常工作。我们收到一些反馈称,如果你无法使网络启动生效,尝试在你的网络中禁用 STP 帧可能有所帮助。

配置网络启动客户端

树莓派 3 B 型号

本节仅适用于树莓派 3 型号 B,因为树莓派 3 型号 B+ 出厂时已启用网络启动功能。

在树莓派 3 型号 B 上实现网络启动之前,需要先从一张带有启用 USB 启动模式配置选项的 SD 卡启动。该操作会在树莓派 SoC 的 OTP(一次性可编程)内存中设置一个位,以启用网络启动。完成此操作后,当无法从 SD 卡启动时,树莓派 3B 将尝试通过 USB 和网络启动。

按照常规方式,在 SD 卡上安装 Raspberry Pi OS Lite 或带桌面的 Raspberry Pi OS。接下来,使用以下命令启用 USB 启动模式:

$ echo program_usb_boot_mode=1 | sudo tee -a /boot/firmware/config.txt

这会添加program_usb_boot_mode=1 to the end of /boot/firmware/config.txt. 使用sudo reboot. After the client Raspberry Pi has rebooted, check that the OTP has been programmed with:

$ vcgencmd otp_dump | grep 17:
17:3020000a

确保输出结果0x3020000a is correct.

客户端配置几乎已完成。最后一步是禁用 USB 启动。运行以下命令:

$ sudo nano /boot/firmware/config.txt

删除包含文本program_usb_boot_mode=1. Finally, shut the client Raspberry Pi down with sudo poweroff.

树莓派 4 型号 B

可以使用raspi-config tool. First, run raspi-config as follows:

$ sudo raspi-config

在……之内raspi-config, choose Advanced Options, then Boot Order, then Network Boot. You must then reboot the device for the change to the boot order to be programmed into the bootloader EEPROM. Atfer the Raspberry Pi reboots, check that the boot order is now 0xf21:

$ vcgencmd bootloader_config

有关配置树莓派 4 引导程序的更多详细信息,请参见树莓派引导程序配置.

以太网 MAC 地址

在配置网络启动前,请记录下序列号和 MAC 地址,以便 TFTP/DHCP 服务器能够识别该开发板。

在树莓派 4 及后续旗舰型号上,MAC 地址在生产时已编程设定,且 MAC 地址与序列号之间无关联。MAC 地址和序列号都会显示在引导程序的HDMI 诊断屏幕上。

要查找以太网 MAC 地址,请运行以下命令:

$ ethtool -P eth0

要查找序列号,请运行以下命令:

$ grep Serial /proc/cpuinfo | cut -d ' ' -f 2 | cut -c 9-16

配置网络启动服务器

将SD卡插入服务器树莓派,然后启动服务器。客户端树莓派需要一个根文件系统来启动:我们将使用服务器根文件系统的副本,并将其放置在/nfs/client1:

$ sudo mkdir -p /nfs/client1
$ sudo apt install rsync
$ sudo rsync -xa --progress --exclude /nfs / /nfs/client1

通过 chroot 进入客户端文件系统以重新生成 SSH 主机密钥:

$ cd /nfs/client1
$ sudo mount --bind /dev dev
$ sudo mount --bind /sys sys
$ sudo mount --bind /proc proc
$ sudo chroot .
$ rm /etc/ssh/ssh_host_*
$ dpkg-reconfigure openssh-server
$ exit
$ sudo umount dev sys proc

查找本地网络的设置。你需要找到路由器(或网关)的地址,可以通过以下命令实现:

$ ip route | awk '/default/ {print $3}'

然后运行:

$ ip -4 addr show dev eth0 | grep inet

你会看到类似如下的输出:

inet 10.42.0.211/24 brd 10.42.0.255 scope global eth0

第一个地址是你的服务器树莓派在网络上的IP地址,斜杠后的部分是网络大小。你的网络极有可能是/24. Also note the brd (broadcast) address of the network. Note down the output of the previous command, which will contain the IP address of the Raspberry Pi and the broadcast address of the network.

最后,记下你的DNS服务器地址,该地址与你的网关地址相同。你可以通过以下命令找到它:

$ cat /etc/resolv.conf

通过systemd networking, which works as the network handler and DHCP server.

为此,你需要创建一个10-eth0.netdev and a 11-eth0.network like so:

$ sudo nano /etc/systemd/network/10-eth0.netdev

添加以下行:

[Match]
Name=eth0

[Network]
DHCP=no

然后创建一个网络文件:

$ sudo nano /etc/systemd/network/11-eth0.network

添加以下内容:

[Match]
Name=eth0

[Network]
Address=10.42.0.211/24
DNS=10.42.0.1

[Route]
Gateway=10.42.0.1

此时你将没有可用的DNS,因此需要把你之前记下的服务器地址添加到systemd/resolved.conf. In this example, the gateway address is 10.42.0.1.

$ sudo nano /etc/systemd/resolved.conf

取消注释DNS行,并在那里添加DNS IP地址。此外,如果你有备用DNS服务器,也请一并添加。

[Resolve]
DNS=10.42.0.1
#FallbackDNS=

为 SSH 连接启用systemd-networkd and then reboot for the changes to take effect:

$ sudo systemctl enable systemd-networkd
$ sudo reboot

现在启动tcpdump so you can search for DHCP packets from the client Raspberry Pi:

$ sudo apt install tcpdump dnsmasq
$ sudo systemctl enable dnsmasq
$ sudo tcpdump -i eth0 port bootpc

将客户端树莓派连接到你的网络并通电。检查大约10秒后客户端的LED灯是否亮起,然后你会收到来自客户端的“DHCP/BOOTP, Request from …​”数据包

IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from b8:27:eb...

现在你需要修改dnsmasq configuration to enable DHCP to reply to the device. Press CTRL + C to exit the tcpdump program, then type the following:

$ echo | sudo tee /etc/dnsmasq.conf
$ sudo nano /etc/dnsmasq.conf

然后替换dnsmasq.conf with:

# Note: comment out port if you want DNS services for systems on the network.
port=0
dhcp-range=10.42.0.255,proxy
log-dhcp
enable-tftp
tftp-root=/tftpboot
pxe-service=0,"Raspberry Pi Boot"

其中dhcp-range line is, use the broadcast address you noted down earlier.

现在创建一个/tftpboot directory:

$ sudo mkdir /tftpboot
$ sudo chmod 777 /tftpboot
$ sudo systemctl enable dnsmasq.service
$ sudo systemctl restart dnsmasq.service

现在监控dnsmasq log:

$ journalctl -f

你应该会看到类似这样的内容:

raspberrypi dnsmasq-tftp[1903]: file /tftpboot/bootcode.bin not found

接下来,你需要将启动文件夹的内容复制到/tftpboot directory.

首先,按下CTRL + C以退出监控状态。然后输入以下内容:

$ cp -r /boot/firmware/* /tftpboot

由于 tftp 位置已更改,请重启dnsmasq:

$ sudo systemctl restart dnsmasq

设置 NFS 根目录

此时应允许你的树莓派客户端尝试启动,直到它试图加载根文件系统(而它本身没有)。

在此时导出/nfs/client1 file system created earlier, and the TFTP boot folder.

$ sudo apt install nfs-kernel-server
$ echo "/nfs/client1 *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports
$ echo "/tftpboot *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee -a /etc/exports

重启 RPC-Bind 和 NFS 服务器,以便它们检测到新文件。

$ sudo systemctl enable rpcbind
$ sudo systemctl restart rpcbind
$ sudo systemctl enable nfs-kernel-server
$ sudo systemctl restart nfs-kernel-server

编辑/tftpboot/cmdline.txt and from root= onwards, and replace it with:

root=/dev/nfs nfsroot=10.42.0.211:/nfs/client1,vers=3 rw ip=dhcp rootwait

你应该将此处的 IP 地址替换为你记录的 IP 地址。同时删除命令行中以init=.

最后,编辑/nfs/client1/etc/fstab and remove the /dev/mmcblk0p1 and p2 lines (only proc should be left). Then, add the boot partition back in:

$ echo "10.42.0.211:/tftpboot /boot/firmware/ nfs defaults,vers=3 0 0" | sudo tee -a /nfs/client1/etc/fstab

如果首次尝试未能成功启动,请持续重试。树莓派启动可能需要一分钟左右,请耐心等待。

使用 IPv6 进行网络启动

通过网络启动 Raspberry Pi 计算机共有 4 个阶段:

  1. 引导加载程序通过 DHCP 协商获取 IP 地址和 TFTP 服务器的详细信息。

  2. 引导加载程序通过 TFTP 加载固件,并将启动过程移交给固件,同时传递网络详细信息。

  3. 固件通过 TFTP 加载内核和命令行。

  4. 内核启动系统的其余部分,通过 NFS 或其他机制加载根文件系统 (rootfs)。

引导加载程序和固件(第 1 至 3 阶段)已增强,以支持通过 IPv6 启动。

IPv6 网络启动是一项实验性 Alpha 功能,根据反馈,我们未来可能需要更改其工作方式。此功能仅适用于 Raspberry Pi 4 和 Compute Module 4。

工作原理

要通过 IPv6 启动,您需要更新版本的固件(例如,start4.elf) and the bootloader. Using the latest release of Raspberry Pi OS and the latest stable bootloader should be sufficient.

常用的dnsmasq DHCP server doesn’t currently support the network boot parameters required for IPv6 network boot, so for the time being you will have to use a different DHCP server such as ISC DHCP.

要挂载rootfs over the network the IPv4 网络启动教程建议使用nfsroot. This doesn’t support IPv6, so another method is needed to mount rootfs over the network.

如果您的 ISP 和路由器不支持 IPv6,您的操作将受到限制。

网络地址

引导加载程序首先发送路由器请求以获取网络详细信息。路由器会响应一个通告数据包,其中包含其以太网地址,如果 TFTP 服务器位于不同网络上,引导加载程序可能需要该地址。

路由器通告包含一个标志,用于指示其 IP 地址是使用有状态(托管)还是无状态(非托管)配置。无状态配置意味着设备自行配置其 IP 地址。目前,引导加载程序会根据其以太网 MAC 地址和路由器提供的网络前缀生成一个地址。

如果路由器指示启用了有状态配置,则使用 DHCP 来获取设备的 IP 地址。这涉及设备向 DHCP 服务器发送请求,服务器以通告进行响应。然后客户端请求该地址,随后收到服务器的回复确认。

DHCP 服务器和客户端使用可变长度的 DUID(设备唯一标识符)来标识自身。在 Raspberry Pi 上,这是从 MAC 地址 (DUID_LL) 派生的。

TFTP 地址

无论使用无状态还是有状态配置,都使用 DHCP 服务器来获取 TFTP 服务器地址。这编码在BOOTFILE-URL parameter. We send the client architecture type value 0x29 to identify a device.

请查看RFC 5970树莓派5IANA IPv6动态主机配置协议文档。

启动过程

此时设备应已获取IP地址和TFTP详细信息。它将下载固件二进制文件start4.elf from the TFTP server and continues running with this. The firmware is passed the IP address and TFTP server details so it can download the kernel and boot the rest of the system.

内核启动

使用IPv4网络启动时,nfsroot is used to mount rootfs over the network. This doesn’t support IPv6 so another solution is required. It might involve a small RAM file system that can mount the appropriate network location before switching to the proper rootfs contents.

通过IPv6使用NFS启动Linux内核的机制仍有待验证。

测试环境搭建

如果您想尝试此操作,需要另一台Raspberry Pi来充当TFTP和DHCP服务器。

理论上,TFTP服务器可以位于任何可路由的网络上,但DHCP服务器必须与其服务的设备处于同一网络中。

TFTP服务器

如果您已有可用的IPv4网络启动配置,可以复用dnsmasq中的TFTP服务器来提供文件(它可同时支持IPv4和IPv6)。

或者,您可以使用独立的TFTP服务器,例如tftpd-hpa.

$ sudo apt install tftpd-hpa
$ sudo systemctl start tftpd-hpa

DHCP服务器

IPv6中的DHCP发生了很大变化。我们需要DHCP至少告知TFTP服务器的地址,在本例中该服务器与DHCP服务器是同一台机器。

$ sudo apt install isc-dhcp-server

修改以下配置/etc/default/isc-dhcp-server

DHCPDv6_CONF=/etc/dhcp/dhcpd6.conf
INTERFACESv6="eth0"

在/etc/dhcp/dhcpd6.conf you need to specify the TFTP server address and setup a subnet. Here the DHCP server is configured to supply some made up unique local addresses (ULA). The host test-rpi4 line tells DHCP to give a test device a fixed address.

not authoritative;

# Check if the client looks like a Raspberry Pi
if option dhcp6.client-arch-type = 00:29 {
        option dhcp6.bootfile-url "tftp://[fd49:869:6f93::1]/";
}

subnet6 fd49:869:6f93::/64 {
        host test-rpi4 {
                host-identifier option dhcp6.client-id 00:03:00:01:e4:5f:01:20:24:0b;
                fixed-address6 fd49:869:6f93::1000;
        }
}

必须为您的服务器分配以下IPv6地址/etc/dhcpcd.conf

interface eth0
static ip6_address=fd49:869:6f93::1/64

现在启动DHCP服务器。

$ sudo systemctl restart isc-dhcp-server.service

引导加载程序

修改配置,指示其尝试通过IPv6而非IPv4进行网络启动。

BOOT_ORDER=0xf21 # 2=Network boot
USE_IPV6=1 # Enable IPv6 network boot
BOOT_UART=1 # Debug

若要恢复IPv4网络启动,只需移除USE_IPV6 line from boot.conf.

路由器

要使用IPv6,您确实需要一台支持IPv6的路由器和ISP。互联网上有一些网站可以为您检查此项,或者您也可以运行以下命令。

sudo apt install ndisc6
rdisc6 -1 eth0

这会向您的路由器发送路由器请求,询问网络详细信息,如网络前缀、路由器以太网地址以及是否使用DHCP进行寻址。如果此命令没有响应,则您的网络和ISP很可能仅支持IPv4。如果支持IPv6,则很可能配置为使用无状态配置,即客户端自行生成地址。

Soliciting ff02::2 (ff02::2) on eth0...
Hop limit                 :           64 (      0x40)
Stateful address conf.    :           No
Stateful other conf.      :          Yes
Mobile home agent         :           No
Router preference         :       medium
Neighbor discovery proxy  :           No
Router lifetime           :          180 (0x000000b4) seconds
Reachable time            :  unspecified (0x00000000)
Retransmit time           :  unspecified (0x00000000)

您或许可以将路由器配置为有状态配置,这意味着它将使用DHCP来获取IP地址。

Hop limit                 :           64 (      0x40)
Stateful address conf.    :          Yes
Stateful other conf.      :          Yes
Mobile home agent         :           No
Router preference         :       medium
Neighbor discovery proxy  :           No
Router lifetime           :          180 (0x000000b4) seconds
Reachable time            :  unspecified (0x00000000)
Retransmit time           :  unspecified (0x00000000)

调试

日志与跟踪

如果启用了启动 UART,您应该能从串口看到类似这样的输出。以 RX6 开头的行表示正在使用 IPv6。

这里dc:a6:32:6f:73:f4 is the MAC address of the TFTP server and it has an IPv6 address of fd49:869:6f93::1. The device itself has a MAC address e4:5f:01:20:24:0b and an IPv6 address of fd49:869:6f93::1000

Boot mode: NETWORK (02) order f
GENET: RESET_PHY
PHY ID 600d 84a2
NET_BOOT: e4:5f:01:20:24:0b wait for link TFTP6: (null)
LINK STATUS: speed: 100 full duplex
Link ready
GENET START: 64 16 32
GENET: UMAC_START 0xe45f0120 0x240b0000
RX6: 12 IP: 1 MAC: 1 ICMP: 1/1 UDP: 0/0 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
NET fd49:869:6f93::1000 tftp fd49:869:6f93::1
RX6: 17 IP: 4 MAC: 4 ICMP: 2/2 UDP: 2/2 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
TFTP_GET: dc:a6:32:6f:73:f4 fd49:869:6f93::1 ab5a4158/start4.elf

RX6: 17 IP: 4 MAC: 4 ICMP: 2/2 UDP: 2/2 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
RX6: 18 IP: 5 MAC: 5 ICMP: 2/2 UDP: 3/3 ICMP_CSUM_ERR: 0 UDP_CSUM_ERR: 0
TFTP_GET: dc:a6:32:6f:73:f4 fd49:869:6f93::1 ab5a4158/config.txt

最后,引导加载程序将控制权交给固件,固件随后会加载内核。

有状态配置

您可以使用 tcpdump 检查网络活动。

$ sudo tcpdump -i eth0 -e ip6 -XX -l -v -vv

以下是 TCP 抓包的一段摘录,其中路由器配置为使用有状态 (DHCP) 网络配置。

设备发送路由器请求。

12:23:35.387046 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:00:00:02 (oui Unknown), ethertype IPv6 (0x86dd), length 70: (hlim 255, next-header ICMPv6 (58) payload length: 16) fe80::e65f:1ff:fe20:240b > ip6-allrouters: [icmp6 sum ok] ICMP6, router solicitation, length 16
          source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
            0x0000:  e45f 0120 240b

路由器发送响应,指示设备使用有状态配置。

12:23:35.498902 60:8d:26:a7:c1:88 (oui Unknown) > 33:33:00:00:00:01 (oui Unknown), ethertype IPv6 (0x86dd), length 110: (hlim 255, next-header ICMPv6 (58) payload length: 56) bthub.home > ip6-allnodes: [icmp6 sum ok] ICMP6, router advertisement, length 56
        hop limit 64, Flags [managed, other stateful], pref medium, router lifetime 180s, reachable time 0ms, retrans timer 0ms
          rdnss option (25), length 24 (3):  lifetime 60s, addr: bthub.home
            0x0000:  0000 0000 003c fe80 0000 0000 0000 628d
            0x0010:  26ff fea7 c188
          mtu option (5), length 8 (1):  1492
            0x0000:  0000 0000 05d4
          source link-address option (1), length 8 (1): 60:8d:26:a7:c1:88
            0x0000:  608d 26a7 c188

设备发送 DHCP 请求。

12:23:35.502517 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown), ethertype IPv6 (0x86dd), length 114: (hlim 255, next-header UDP (17) payload length: 60) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp sum ok] dhcp6 solicit (xid=8cdd56 (client-ID hwaddr type 1 e45f0120240b) (IA_NA IAID:0 T1:0 T2:0) (option-request opt_59) (opt_61) (elapsed-time 0))

DHCP 服务器回复通告。

12:23:35.510478 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown), ethertype IPv6 (0x86dd), length 172: (flowlabel 0xad54d, hlim 64, next-header UDP (17) payload length: 118) fe80::537a:52c:c647:b184.dhcpv6-server > fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd886 -> 0x6d26!] dhcp6 advertise (xid=8cdd56 (IA_NA IAID:0 T1:3600 T2:7200 (IA_ADDR fd49:869:6f93::1000 pltime:604800 vltime:2592000)) (client-ID hwaddr type 1 e45f0120240b) (server-ID hwaddr/time type 1 time 671211709 dca6326f73f4) (opt_59))

设备向 DHCP 服务器发送请求,获取地址和 TFTP 详细信息。

12:23:35.510763 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown), ethertype IPv6 (0x86dd), length 132: (hlim 255, next-header UDP (17) payload length: 78) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp sum ok] dhcp6 request (xid=8cdd56 (client-ID hwaddr type 1 e45f0120240b) (server-ID hwaddr/time type 1 time 671211709 dca6326f73f4) (IA_NA IAID:0 T1:0 T2:0) (option-request opt_59) (opt_61) (elapsed-time 1))

DHCP 服务器回复,opt_59 is used to pass the address of the TFTP server.

12:23:35.512122 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown), ethertype IPv6 (0x86dd), length 172: (flowlabel 0xad54d, hlim 64, next-header UDP (17) payload length: 118) fe80::537a:52c:c647:b184.dhcpv6-server > fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd886 -> 0x6826!] dhcp6 reply (xid=8cdd56 (IA_NA IAID:0 T1:3600 T2:7200 (IA_ADDR fd49:869:6f93::1000 pltime:604800 vltime:2592000)) (client-ID hwaddr type 1 e45f0120240b) (server-ID hwaddr/time type 1 time 671211709 dca6326f73f4) (opt_59))

设备向 FTP 服务器发送邻居请求,因为它需要其 MAC 地址。

12:23:36.510768 e4:5f:01:20:24:0b (oui Unknown) > 33:33:ff:00:00:01 (oui Unknown), ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::e65f:1ff:fe20:240b > ff02::1:ff00:1: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has fd49:869:6f93::1
          source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
            0x0000:  e45f 0120 240b

FTP 服务器回复其 MAC 地址。

12:23:36.510854 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown), ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload length: 32) fd49:869:6f93::1 > fe80::e65f:1ff:fe20:240b: [icmp6 sum ok] ICMP6, neighbor advertisement, length 32, tgt is fd49:869:6f93::1, Flags [solicited, override]
          destination link-address option (2), length 8 (1): dc:a6:32:6f:73:f4
            0x0000:  dca6 326f 73f4

设备发出 TFTP 请求,现在应该通过网络启动了。

12:23:36.530820 e4:5f:01:20:24:0b (oui Unknown) > dc:a6:32:6f:73:f4 (oui Unknown), ethertype IPv6 (0x86dd), length 111: (hlim 255, next-header UDP (17) payload length: 57) fd49:869:6f93::1000.61785 > fd49:869:6f93::1.tftp: [udp sum ok]  49 RRQ "ab5a4158/start4.elf" octet tsize 0 blksize 1024

无状态配置

以下是无状态(非 DHCP)网络配置的 tcp 抓包摘录。

设备发送路由器请求。

12:55:27.541909 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:00:00:02 (oui Unknown), ethertype IPv6 (0x86dd), length 70: (hlim 255, next-header ICMPv6 (58) payload length: 16) fe80::e65f:1ff:fe20:240b > ip6-allrouters: [icmp6 sum ok] ICMP6, router solicitation, length 16
          source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
            0x0000:  e45f 0120 240b

路由器回复网络详细信息。

12:55:27.834684 60:8d:26:a7:c1:88 (oui Unknown) > 33:33:00:00:00:01 (oui Unknown), ethertype IPv6 (0x86dd), length 174: (hlim 255, next-header ICMPv6 (58) payload length: 120) bthub.home > ip6-allnodes: [icmp6 sum ok] ICMP6, router advertisement, length 120
        hop limit 64, Flags [other stateful], pref medium, router lifetime 180s, reachable time 0ms, retrans timer 0ms
          prefix info option (3), length 32 (4): 2a00:23c5:ee00:5001::/64, Flags [onlink, auto, router], valid time 300s, pref. time 120s
            0x0000:  40e0 0000 012c 0000 0078 0000 0000 2a00
            0x0010:  23c5 ee00 5001 0000 0000 0000 0000
          prefix info option (3), length 32 (4): fd4d:869:6f93::/64, Flags [onlink, auto, router], valid time 10080s, pref. time 2880s
            0x0000:  40e0 0000 2760 0000 0b40 0000 0000 fd4d
            0x0010:  0869 6f93 0000 0000 0000 0000 0000
          rdnss option (25), length 24 (3):  lifetime 60s, addr: bthub.home
            0x0000:  0000 0000 003c fe80 0000 0000 0000 628d
            0x0010:  26ff fea7 c188
          mtu option (5), length 8 (1):  1492
            0x0000:  0000 0000 05d4
          source link-address option (1), length 8 (1): 60:8d:26:a7:c1:88
            0x0000:  608d 26a7 c188

设备向 DHCP 多播地址发送信息请求,询问 TFTP 详细信息。

12:55:27.838300 e4:5f:01:20:24:0b (oui Unknown) > 33:33:00:01:00:02 (oui Unknown), ethertype IPv6 (0x86dd), length 98: (hlim 255, next-header UDP (17) payload length: 44) fe80::e65f:1ff:fe20:240b.dhcpv6-client > ff02::1:2.dhcpv6-server: [udp sum ok] dhcp6 inf-req (xid=e5e0a4 (client-ID hwaddr type 1 e45f0120240b) (option-request opt_59) (opt_61) (elapsed-time 0))

DHCP 服务器回复 TFTP 服务器详细信息(opt_59).

12:55:27.838898 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown), ethertype IPv6 (0x86dd), length 150: (flowlabel 0xd1248, hlim 64, next-header UDP (17) payload length: 96) fe80::537a:52c:c647:b184.dhcpv6-server > fe80::e65f:1ff:fe20:240b.dhcpv6-client: [bad udp cksum 0xd870 -> 0x78bb!] dhcp6 reply (xid=e5e0a4 (client-ID hwaddr type 1 e45f0120240b) (server-ID hwaddr/time type 1 time 671211709 dca6326f73f4) (opt_59))

设备请求 TFTP 服务器的 MAC 地址,因为它可以判断两者位于同一网络。

12:55:28.834796 e4:5f:01:20:24:0b (oui Unknown) > 33:33:ff:1d:fe:2a (oui Unknown), ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload length: 32) fe80::e65f:1ff:fe20:240b > ff02::1:ff1d:fe2a: [icmp6 sum ok] ICMP6, neighbor solicitation, length 32, who has 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a
          source link-address option (1), length 8 (1): e4:5f:01:20:24:0b
            0x0000:  e45f 0120 240b

FTP 服务器回复其 MAC 地址。

12:55:28.834875 dc:a6:32:6f:73:f4 (oui Unknown) > e4:5f:01:20:24:0b (oui Unknown), ethertype IPv6 (0x86dd), length 86: (hlim 255, next-header ICMPv6 (58) payload length: 32) 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a > fe80::e65f:1ff:fe20:240b: [icmp6 sum ok] ICMP6, neighbor advertisement, length 32, tgt is 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a, Flags [solicited, override]
          destination link-address option (2), length 8 (1): dc:a6:32:6f:73:f4
            0x0000:  dca6 326f 73f4

设备开始发出 TFTP 请求。

12:55:28.861097 e4:5f:01:20:24:0b (oui Unknown) > dc:a6:32:6f:73:f4 (oui Unknown), ethertype IPv6 (0x86dd), length 111: (hlim 255, next-header UDP (17) payload length: 57) 2a00:23c5:ee00:5001:e65f:1ff:fe20:240b.46930 > 2a00:23c5:ee00:5001:57f1:7523:2f1d:fe2a.tftp: [udp sum ok]  49 RRQ "ab5a4158/start4.elf" octet tsize 0 blksize 1024