# 树莓派无界面初始化(headless)

## 1\. 刻录SD卡

镜像下载 [https://www.raspberrypi.com/software/operating-systems/](https://www.raspberrypi.com/software/operating-systems/) [https://shumeipai.nxez.com/download](https://shumeipai.nxez.com/download)

刻录器下载 [https://www.balena.io/etcher#download-etcher](https://www.balena.io/etcher#download-etcher)

刻录后，SD卡中有一个boot分区和一个ext分区。

## 2\. 配置网络和ssh

我们需要在boot分区的根目录下编辑三个文件：`ssh`，`wpa_supplicant.conf`，`userconf.txt`。 树莓派启动后会把这几个文件从boot分区删除，将其内容写入ext分区中。

### 2.1 开启ssh

为了开启ssh-server，需要创建一个名为`ssh`的空文件。

### 2.2 wifi配置

为了连接wifi，需要创建一个名为`wpa_supplicant.conf`的文件，其内容为：

```apache
country=CN
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
	ssid="WiFi-A"
	psk="12345678"
	priority=1
}
network={
	ssid="WiFi-B"
	psk="12345678"
	priority=2
}
```

参考 [https://segmentfault.com/a/1190000010976507](https://segmentfault.com/a/1190000010976507)

### 2.3 创建用户

为了建立用户，需要创建`userconf.txt`文件，其内容为：

```plaintext
pi:$6$/4.VdYgDm7RJ0qM1$FwXCeQgDKkqrOU3RIRuDSKpauAbBvP11msq9X58c8Que2l1Dwq3vdJMgiZlQSbEXGaY5esVHGBNbCxKLVNqZW1
```

这里对应的用户名是pi，密码是raspberry。 冒号前面的pi就是初始化用户名，后面的就是加密后的初始密码raspberry。

参考 [https://blog.csdn.net/shamqu/article/details/124920129](https://blog.csdn.net/shamqu/article/details/124920129)

## 3\. 登录

将树莓派连接电源，等待一段时间待其开机，然后用`ssh pi@<IP>`登录树莓派。

找到`<IP>`具体值的方法有多种：

1. 电脑和树莓派连接同一个wifi路由器。 树莓派会自动在路由器上让`raspberrypi`指向自己的ip。 所以在电脑上用 `ssh pi@raspberrypi` 就可以登录树莓派。
    
2. 或者去路由器的后台管理页面找树莓派的ip。 如果ip是`192.168.0.123`，那么就`ssh pi@192.168.0.123`。
    
3. 或者`nmap -p 22 192.168.0.0/24`扫描网段中开启22端口的ip。
    

## 4\. 镜像源配置

清华镜像源: [https://mirrors.tuna.tsinghua.edu.cn/help/raspbian/](https://mirrors.tuna.tsinghua.edu.cn/help/raspbian/)
