第 9 節

Other operations

0瀏覽次數0訪問次數--跳出率--平均停留

How to connect the industrial computer to Wi-Fi

When our industrial computer moves from one environment to another, and we haven't connected to the Wi-Fi in the new environment, how can we get the industrial computer online without a screen?

Navigate to the hard drive directory of the industrial computer, enter /etc/netplan/, where there are many yaml files. Find the one that best matches the format below:

network: 
  version: 2 
  wifis: 
    NM-6f414fe0-2658-48ff-89ee-c7981b87bc96: 
      renderer: NetworkManager 
      match: 
        name: "wlan0" 
      dhcp4: true 
      dhcp6: true 
      access-points: 
        "EMIS_Vinci_Robocon_5G": 
          auth: 
            key-management: "psk" 
            password: "vinci666" 
          networkmanager: 
            uuid: "6f414fe0-2658-48ff-89ee-c7981b87bc96" 
            name: "EMIS_Vinci_Robocon_5G" 
            passthrough: 
              wifi-security.auth-alg: "open" 
              ipv6.addr-gen-mode: "default" 
              ipv6.ip6-privacy: "-1" 
              proxy._: "" 
      networkmanager: 
        uuid: "6f414fe0-2658-48ff-89ee-c7981b87bc96" 
        name: "EMIS_Vinci_Robocon_5G"

Change it to the new Wi-Fi name and password:

network:
  version: 2
  wifis:
    wlan0:
      dhcp4: true
      dhcp6: true
      access-points:
        "EMIS_Vinci_Robocon_5G":
          password: "vinci666"

The industrial computer connects to the internet as soon as it boots up.

SSH remote development

Environment Setup

1. Hardware Preparation

First, you need an industrial computer (X86 small computer, professional industrial computer, Raspberry Pi, etc.).

The hardware carriers of control systems are diverse, with commonly used processors based on architectures such as ARM and x86, for example: PCs, industrial PCs, Raspberry Pi, NVIDIA Jetson, and so on. Different processors have their own advantages and disadvantages. PCs and industrial PCs offer powerful processing performance but come with high power consumption, large size, and poor flexibility, while embedded systems are the opposite. For us, we can autonomously select an appropriate control system based on various factors of the robot platform, such as electrical requirements, load capacity, space, and intended use.

Regardless of which processor is chosen, as long as Robot Operating System (ROS) or ROS2 is installed for robot development, there is no fundamental difference in usage for developers. In other words, as a software engineer, in some scenarios, there is no need to focus on hardware selection.

2. Setting a Static IP

When connecting remotely, regardless of the tool used, you need to locate the target host by its IP address and then log in using an account and password. Therefore, we first need to obtain that IP address. Since the IP is required for every connection, to ensure convenience and stability, it is best to set the target host's IP address as a static IP. The specific steps are as follows.

  1. Enter the settings interface

Start the connected host machine (a monitor or HDMI capture card is required during startup; after configuring SSH remote access, the monitor or HDMI capture card is no longer needed), and enter the settings interface.

  1. Configure the connected network

  1. Set a Static IP

Check the current IP address.

Set a static IP.

At this point, the IP configuration is complete.

Environment Setup

Concept

SSH (Secure Shell) is a versatile, powerful, software-based network security solution. Every time a computer sends data over the network, SSH automatically encrypts it. When the data reaches its destination, SSH automatically decrypts the encrypted data. The entire process is transparent, and using OpenSSH tools will enhance your system's security. SSH is easy to install and simple to use.

Implementation

The SSH implementation architecture is divided into two main parts: the client and the server. The client is the sender of data, and the server is the receiver. In this scenario, we need to send data from the local host to the remote host. Therefore, the local host needs to install and start an SSH client, while the remote host needs to install and start an SSH server. The specific implementation process is as follows:

  1. Install the SSH client on the local host and the SSH server on the remote host.
  2. Start the SSH service on the remote host.
  3. Log into a remote host from a local machine.
  4. Implement data transmission.
  5. Install SSH client and server

By default, the Ubuntu system already has the SSH client installed, so you only need to install the SSH server on the remote host. The installation command is as follows:

 sudo apt install openssh-server

If the SSH client needs to be installed manually, run the following command:

sudo apt install openssh-client
  1. Start the SSH service on the remote host

The command to start the SSH service on a remote host is as follows:

sudo /etc/init.d/ssh start

After starting, you can use the following command to check whether the service is running properly:

ps -e | grep ssh

If startup is successful, it will include the sshd program.

If you need to frequently use SSH for remote login, to simplify the process, you can configure the SSH service on the remote host to start automatically at boot. The command is as follows:

sudo systemctl enable ssh
  1. Local Remote Login

To log into a remote host, you can use the following command:

ssh -X 用户名@ip地址

Then, follow the prompt to enter the login password, and you will be successfully logged in.

If you want to exit, you can call the exit command:

exit

4. Implementing Data Transmission

By using SSH on the local host, you can easily upload or download data to and from a remote host by simply calling the relevant commands. The command format is as follows:

The format for the file upload command is as follows:

scp 本地文件路径 账号@ip:路径

The command format for uploading a folder is as follows:

scp -r 本地文件夹路径 账号@ip:路径

The download file command format is as follows:

scp 账号@ip:路径 本地文件夹路径

The download folder command format is as follows:

scp -r 账号@ip:路径 本地文件夹路径

Optimization

Every time you log in remotely, you need to enter a password, which is inconvenient. You can use SSH keys to simplify the login process, enabling passwordless login and improving operational efficiency. The idea is to generate a pair of public and private keys: the private key is stored locally, and the public key is uploaded to the server. Each time you log in, the local machine sends the private key to the server. If the server has a matching public key, it recognizes you as a legitimate user and establishes an SSH connection directly. The implementation involves only two steps:

  1. Generate a local key pair.
  2. Upload the public key to the remote host.

1. Generate a key pair

Local client generates public and private keys: (just press Enter all the way to accept defaults)

ssh-keygen

The command above will create a public-private key pair in the .ssh folder under the user's home directory.

  1. id_rsa (private key);
  2. id_rsa.pub (public key).

2. Uploading the Public Key

The upload instructions are as follows:

ssh-copy-id -i ~/.ssh/id_rsa.pub 账号@ip

This command uploads the local public key to the SSH directory on the remote host, where the authorized_keys file stores the public key content.

From now on, you won't need to enter a password for remote logins.

Optimizing with VSCode

In the previous section, we introduced the use of SSH remote connections. However, using SSH alone has some limitations. For example, editing file content requires the vi editor, and within a single terminal, you cannot edit multiple files simultaneously. This section will introduce a more practical feature — remote development using VSCode combined with plugins. This allows us to perform remote development in a graphical way, making it more convenient and faster than using SSH alone, and can greatly improve program development efficiency.

1. Preparation

VScode remote development relies on SSH. Please first configure the SSH remote connection according to the previous section.

2. Install the Remote Development Plugin for VSCode

Launch VScode, first click the Extensions button in the sidebar, then type Remote Development into the search bar of 扩展:商店 and click the plugin with the same name, and finally click 安装 in the display area on the right.

3. Configure Remote Connection

Step 1: Use the shortcut ctrl + shift + p to open the command input window, then enter Remote-SSH:Connect to Host.... From the pop-up list, select the option with the same name.

Step 2: After Step 1 is completed, a new command window will pop up as shown below. Select Add New SSH Host from the dropdown list.

Step 3: After completing step 2, a new command window will pop up. In it, enter: ssh -X ubuntu@192.168.43.164, where ubuntu needs to be replaced with your login username, and 192.18.43.164 should be replaced with the IP address of the remote host you are connecting to.

Step 4: Select the first option in the pop-up list after completing Step 3 (or simply press Enter) to finish the configuration. A confirmation message will appear once the configuration is successful.

4. Usage

Step 1: Continue using the shortcut ctrl + shift + p to open the command input window, and enter Remote-SSH:Connect to Host.... The list will then display the IP address configured in step 3. Select it directly, and after selection, VScode will open a new window.

Alternatively, you can click 远程资源管理器 in the sidebar, select the server you want to connect to from the pop-up server list, right-click it, and choose to establish a remote connection in the current window or a new window.

Step 2: Select 打开文件夹 under the 文件 menu bar, choose the folder you want to open from the pop-up list, and click OK.

Finally, we can achieve remote development just like working with local files.

Remote Desktop

Because X11 forwarding is far too inefficient, it's necessary to use remote desktop access to view Rviz2, Gazebo, and similar tools (if needed).

We choose to use VNC to view it.

  1. Install the VNC server:

Here, TigerVNC is used as an example for installation:

sudo apt install tigervnc-standalone-server tigervnc-common
  1. Set VNC password:

To set a password for the VNC user, run the following command:

vncpasswd
  1. Configure the VNC startup script:

Create a VNC configuration file and create a startup file in the .vnc folder within the user's home directory:

mkdir -p ~/.vnc
nano ~/.vnc/xstartup

In the opened editor, enter the following content (using GNOME as an example):

#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
gnome-session

Save and exit (in nano, press Ctrl + O to save, then press Ctrl + X to exit).

  1. Grant execute permission:

Set execute permission for the xstartup file:

chmod +x ~/.vnc/xstartup
  1. Start the VNC server:
vncserver -geometry 1920x1080 -localhost=0

The geometry option specifies the window size, and the localhost option is set to 0 to allow external connections. (Setting it to 1 only allows local connections.)

You will see output similar to :1, which indicates the display number of the VNC session. For example, if the output is :1, the VNC listening port is 5901 (5900 + display number).

  1. Check the enabled VNC servers:
vncserver -list

  1. Connect to the VNC server:

Use a VNC client (such as vncviewer) to connect to the VNC server by entering your server's IP address and port. For example, if the server IP is 192.168.31.10 and the display number is 1, you should connect to 192.168.31.10:1, or simply enter 192.168.31.10:5901.

  1. Stop the VNC server:

If you need to stop the VNC server, you can use the following command:

vncserver -kill :1

Replace :1 with the actual display number you are using.

USB port settings

First, configure the permissions.


# 将用户权限提高
sudo usermod -aG dialout $USER
newgrp dialout

# 查看下面命令是否输出dialout(若输出才正常)
groups

Because we plug and unplug USB devices, their port numbers may keep changing, so we need to assign a fixed alias to their tty.

Bind USB devices by port (multiple different devices)

Requirement: A radar and a smart car are now connected to the Ubuntu system. Please bind ports for both.

Implementation Principle: Port binding can be achieved through the "identifier" of the USB device itself.

The process is as follows:

(1). Find the device idVendor and idProduct

Connect two USB devices, and in the terminal run the command lsusb to view the USB device information in the system as well as the devices connected to it.

As shown in the image above, the data inside the red box represents USB devices. The values following the ID 1a86:7523 are the USB idVendor and idProduct respectively (the two parameters are separated by a colon).

Additionally: You can determine which data corresponds to the connected USB device by comparing results after re-plugging.

(2). Write mapping rules

Create a new file named xxx.rules (customize the filename) in the /etc/udev/rules.d directory.

sudo vim /etc/udev/rules.d/xxx.rules

I'd be happy to help, but it looks like you didn't include the content you want me to translate. Could you please provide the Simplified Chinese Markdown fragment you'd like me to translate into natural American English?

KERNEL=="ttyUSB*", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", MODE:="0777", SYMLINK+="mylidar"
KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE:="0777", SYMLINK+="mycar"

Code Explanation

  • KERNEL is a fixed kernel name, which here is uniformly "ttyUSB*".
  • MODE is a node permission, typically set to "0777", indicating read, write, and execute permissions.
  • A SYMLINK is a symbolic link, which is an alias for a binding.
  • ATTRS is the unique identifier for the device manufacturer, and idVendor together with idProduct form the device ID found via lsusb above.

Tip: Most USB device vendors provide similar script files. For the caller, simply copy the file to the /etc/udev/rule.d directory.

Device TypeKernel name exampleExplanation
USB serial devicettyUSB*USB to serial device, such as /dev/ttyUSB0
Serial port devicettyS*Physical serial port device, such as /dev/ttyS0
Storage devicesd*SCSI disk device, such as /dev/sda
Network deviceeth*Ethernet device, such as /dev/eth0
Input deviceevent*Input event device, such as /dev/input/event0
Bluetooth devicerfcomm*Bluetooth serial device, such as /dev/rfcomm0

(3). Apply the rules.

Enter the following command in the terminal:


# Ubuntu用下方命令
sudo service udev reload
sudo service udev restart

#Fedora用下方命令
sudo udevadm control --reload
sudo udevadm trigger

Simply re-plug the device.

(4). Test

Enter the following command in the terminal:

ll /dev | grep ttyUSB

The execution result is as follows:

You can also plug and unplug the USB device multiple times. You'll notice that the number n in the device port ttyUSBn changes, but the alias always points to the corresponding USB device. At this point, you can use the alias to associate the USB device you need.

Disadvantages:

The above implementation also has certain limitations. When Ubuntu is connected to two or more USB devices of the same model, since the device IDs are identical, this implementation will only take effect for one of them. In such cases, the second strategy is needed to achieve port binding.

Bind ports based on host hardware (multiple identical devices)

Requirement: Two identical radar units are now connected to the unmanned vehicle, one at the front and one at the rear. Please bind ports for both.

Implementation Principle: The USB interface of the host to which a USB device is connected also has its own "identifier," which can be used to implement port binding.

The process is as follows:

(1). Check the KERNELS of the USB interface on the connected host.

Run the following command to view the USB information of the first radar:

udevadm info --attribute-walk --name=/dev/ttyUSB0 | grep KERNELS
udevadm info --attribute-walk --name=/dev/ttyACM0 | grep KERNELS

Run the following command to view the USB information of the second LiDAR:

udevadm info --attribute-walk --name=/dev/ttyUSB1 | grep KERNELS

Comparing the results across different KERNELS, the first radar port address is KERNELS==1-1.3:1.0, and the second radar port address is KERNELS==1-1.4:1.0. This data can be used as a "unique identifier" for different ports.

(2). Write mapping rules

In the /etc/udev/rules.d directory, create a new file named xxx.rules (customize the filename) and enter the following content:

sudo vim /etc/udev/rules.d/xxx.rules
KERNEL=="ttyUSB*", KERNELS=="1-1.3:1.0", MODE:="0777", SYMLINK+="rplidar_front"
KERNEL=="ttyUSB*", KERNELS=="1-1.4:1.0", MODE:="0777", SYMLINK+="rplidar_back"

(3). Apply the rules.

Enter the following command in the terminal:


# Ubuntu用下方命令
sudo service udev reload
sudo service udev restart

#Fedora用下方命令
sudo udevadm control --reload
sudo udevadm trigger

Simply re-plug the device.

(4). Test

Enter the following command in the terminal, and the output will be as follows:

ll /dev | grep ttyUSB

At this point, you can use an alias to associate the USB device you need.

Drawbacks: USB devices must be connected to the host's designated ports; otherwise, port binding may fail or logic errors may occur. (Additionally, adding new devices may cause port changes.)

Bind ports based on other attributes

(1). View the information about the USB ports on the connected host.

udevadm info -a -p $(udevadm info -q path -n /dev/ttyACM0)
udevadm info -a -p $(udevadm info -q path -n /dev/ttyUSB0)

These data will not change, so they can be used as identifiers.

(2). Write mapping rules

In the /etc/udev/rules.d directory, create a new file named xxx.rules (customize the filename) and enter the following content:

sudo vim /etc/udev/rules.d/xxx.rules
KERNEL=="ttyACM*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d4", ATTRS{serial}=="0001", MODE:="0777", SYMLINK+="ttyACM_Lidar"
KERNEL=="ttyACM*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d4", ATTRS{serial}=="0002", MODE:="0777", SYMLINK+="ttyACM_MCU"
KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE:="0777", SYMLINK+="ttyUSB_IMU"

(3). Apply the rules.

Enter the following command in the terminal:


# Ubuntu用下方命令
sudo service udev reload
sudo service udev restart

#Fedora用下方命令
sudo udevadm control --reload
sudo udevadm trigger

Simply reconnect the device, or restart the system directly.

(4). Test

In the terminal, enter the following command: ll /dev|Run grep ttyUSB, the result is as follows:

At this point, you can use an alias to associate the USB device you need.

Drawbacks: Some devices may not have a serial port number, etc.

Other Precautions

Not all USB device port numbers follow the ttyUSBn format. For example, an Arduino's port number might be ttyACMn, and for a USB camera, a single device corresponds to two port numbers: videon and video(n+1). Typically, the videon port is used to enable the camera device, and that is also the interface that needs to be associated when binding.

However, regardless of which USB device is connected externally, and no matter which of the two methods mentioned above is used for port binding, the underlying principle is similar — only the implementation details differ. If an external Arduino device is connected, then in the rules file, KERNEL=="ttyUSB*" should be changed to KERNEL=="ttyACM*". If a USB camera is connected externally, then in the rules file, KERNEL=="ttyUSB*" should be changed to a format similar to KERNEL=="video[0,2,4,6]", where video[0,2,4,6] indicates that the bindable ports are video0 or video2 or video4 or video6.

Linux Partition GUI Tool

sudo apt install gparted
sudo dnf install gparted

DDNS

Mount the intranet webpage

You can mount local web pages on the router, or on other devices within the same local network segment, and even mount them locally.

Below, using an Android device as an example: since Android devices cannot directly open HTML files for now, we can host the HTML on a local server and then view it through a browser.

Since the Android system is based on the Linux kernel, we can download an app called Termux to run some Linux commands:

https://github.com/termux/termux-app

First, after opening the app, update the software cache:

pkg update

Then change the source.

nano $PREFIX/etc/apt/sources.list

Replace the content of this file with the following:

deb https://mirrors.bfsu.edu.cn/termux/termux-packages-24 stable main
  • If you are using the nano editor:
    • Save the file as Ctrl+O.
    • Confirm the filename according to Enter.
    • Press Ctrl+X to exit the editor.
  • If you are using the vim editor:
    • Press Esc to exit edit mode.
    • Press :wq to save and exit.

Next, update the software sources again:

pkg update && pkg upgrade

Install Python

pkg install python3

Accessing Device Storage via Termux

If the file is on an Android device, you can use Termux's file manager to access the device's storage:

termux-setup-storage
  1. Navigate to the directory containing the HTML file:
    1. Use the cd command to enter the directory where the HTML file is located:
cd ~/your_html_folder
  1. Start Python HTTP Server
    1. Run the following command to start a simple HTTP server:
    python3 -m http.server 8000
    
    1. This will start a web server on port 8000.
  • After starting the server, Termux will display log information, for example:
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
  • This indicates the server has started successfully.

Accessing an HTML file in a browser

  1. Accessing on the same device :
    1. Open the browser on your Android device (such as Chrome) and enter the following address:
    http://localhost:8000
    
    1. If the HTML file contains index.html, it will load automatically; otherwise, you need to manually click the file link.

RustDesk

RustDesk unattended remote control

Currently, RustDesk cannot perform unattended operations under Wayland, so we need to disable login passwords, screen lock, and sleep/standby entirely.

Set up KDE6 automatic login
  1. You can first check your SDDM type.
ls /usr/share/xsessions/
ls /usr/share/wayland-sessions/

Check which one outputs content; the folder that outputs content is the SDDM you have. For example, if xsessions outputs content, then it's the X11 SDDM. If wayland-sessions outputs content, then you have the Wayland SDDM.

  1. Edit the SDDM configuration:
sudo nano /etc/sddm.conf

At the very top of the file, there is a section called Autologin. Add the following content underneath it:

[Autologin]
User=你的用户名
Session=plasma.desktop   # 或 plasma.desktop(X11),方案一可用 Wayland
  1. Save and exit, then restart SDDM:
sudo systemctl restart sddm

✅ Automatically logs into the desktop after startup, no password required.

To disable the lock screen in KDE6 system settings:

Open System Settings → Screen Locking. Disable auto-lock Turn off the screen / Screen saver lock This way, RustDesk can directly control the desktop after booting, without being blocked by the lock screen.

Disable sleep system settings → Power Management

Disable "Sleep" or "Auto-Suspend" Ensure the computer stays online at all times, so RustDesk can be remotely controlled at any time. If you must use hibernation, you can disable it in the BIOS settings to ensure the device connects to the network immediately upon startup.

RustDesk self-hosted server

Install on the server side
Command line method
  1. Open the official website: https://rustdesk.com/docs/zh-cn/self-host/

alt text

  1. To access the server where you need to install RustDesk via SSH.
ssh tungchiahui@10.0.0.4

alt text

  1. Use the command from method two.

alt text

wget https://raw.githubusercontent.com/techahold/rustdeskinstall/master/install.sh
chmod +x install.sh
./install.sh

See the next section for the ./install.sh setup.

  1. Configuring and Viewing the KEY

Here, if you want to directly use a public IP, select 1)IP; if you are using DDNS or similar to bind a domain name to an IP address, select 2).

alt text

This selects 2)No.

alt text

Copy this KEY down, as you'll need it later during software configuration.

alt text

  1. Configure the firewall
    1. If you are a Debian-based system Install the firewall
    sudo apt install ufw
    

Configure the firewall ```bash sudo ufw allow 22

ufw allow 21114:21119/tcp
ufw allow 21116/udp
sudo ufw enable
```
2. If you are using a RHEL-based system

Install the firewall bash # 如果你是RHEL系 sudo dnf install firewalld sudo systemctl enable --now firewalld

Configure the firewall ```bash sudo firewall-cmd --add-port=22/tcp --permanent sudo firewall-cmd --reload

sudo firewall-cmd --add-port=21114-21119/tcp --permanent
sudo firewall-cmd --reload

sudo firewall-cmd --add-port=21116/udp --permanent
sudo firewall-cmd --reload

sudo systemctl enable --now firewalld
```
1Panel method
  1. Search for RustDesk in the panel and install it.

alt text

  1. Configure the firewall

alt text

Add a few ports. alt textalt textalt text

  1. View KEY alt text

Copy KEY

alt text

After setting up your own server, configure the RustDesk software.
  1. PC side

alt text

alt text

If "Ready" appears, the configuration is successful. alt text

  1. Mobile

alt text

alt text

Points to note

If you are using a home internal network server, you also need to configure the router to allow the corresponding ports.

Find the OpenWrt firewall settings and click Add. alt text

alt text

alt text

Only then can your server port be truly and successfully unblocked.

WireGuard

Introduction

WireGuard是用于在室外通过VPN来访问内网设备的一种工具.

这里我的教程将会教你如何在室外访问你家里的内网设备.

我的环境

内网

家庭内网网段:10.0.0.0/24

alt text

外部设备

如果你是在办公室等地方链接办公室的wifi,那么你需要知道室外内网网段,如果你直接用手机数据流量的话,那么什么都不需要知道.

室外内网网段:192.168.31.0/24

室外数据流量运营商:中国联通

Install

服务端-软路由端

SSH登录OpenWrt,或者用LuCI界面:

opkg update
opkg install wireguard-tools luci-proto-wireguard kmod-wireguard qrencode

装完刷新一下浏览器LuCI页面.

客户端-手机,电脑端

https://www.wireguard.com/install/

  1. Android

https://play.google.com/store/apps/details?id=com.wireguard.android&hl=zh&pli=1

  1. iOS

美区:https://apps.apple.com/us/app/wireguard/id1441195209

日区:https://apps.apple.com/jp/app/wireguard/id1441195209

台区:https://apps.apple.com/tw/app/wireguard/id1441195209

  1. Linux
    1. Fedora
     sudo dnf install wireguard-tools
    
    1. Ubuntu/Debian
sudo apt install wireguard

配置

服务端-初始化配置

在luci界面中,点击网络 → 接口 → 添加新接口

  1. 协议选 WireGuard VPN
  1. 名称填 wg0
  1. 点下一步,进到详情页

alt text

按照上图的步骤,依次配置.

这里解释一下.

监听端口:51820(可自定义,使用一个未被占用的端口即可,记住这个端口,不懂的话就照我的设置)

IP地址:10.10.10.1/24(VPN内网网段,跟你软路由的局域网段不能冲突,不懂的话就照我的设置)

你必须确保你的家庭内网网段和你的室外内网网段以及刚才填的那个IP地址不能属于同一网段.

比如我的家庭内网网段10.0.0.0/24,而室外内网网段192.168.31.0/24,VPN的网段10.10.10.0/24.

然后点击防火墙设置,选择WireGuard.

alt text

服务端-对端配置

这里配置的就是你的手机/笔记本作为客户端连进来的信息:

这个界面很方便,LuCI可以直接帮你生成客户端的密钥对并直接导出配置文件/二维码,不需要你手动在手机上先生成公钥再倒腾过来,效率高很多。按下面顺序填:

  1. description phone (或者你自己好记的名字,比如"iPhone17")
  1. 公钥 + 私钥 —— 直接点"生成新的密钥对"

点这个按钮,系统会自动帮你同时生成一对新的公钥+私钥,并自动填到"公钥"和"私钥"两个框里。

这个做法比你自己在手机App里生成再抄公钥过来省事得多,因为最后可以直接导出完整配置文件甚至二维码给手机扫码导入,私钥也是配置好的,不用手动输入。

  1. 预共享密钥(PSK) —— 建议点"生成预共享密钥"

这是可选的额外加密层,加上更安全(抗未来量子计算破解),点一下"生成预共享密钥"按钮自动填好即可,不需要手动操作。

  1. 允许的IP

点绿色+号,填:

10.10.10.2/32 这是分配给这台手机的隧道内网IP(如果以后要加第二台设备,比如笔记本,就用10.10.10.3/32,以此类推)。

  1. 为允许的IP创建路由 —— 勾选

这个决定了服务端要不要给这个IP自动建路由,勾上,否则服务端不知道怎么把去往10.10.10.2的包转发给这个peer。

  1. 对端地址 (Image 2)

这个字段填的是客户端的地址,但因为你的手机是移动设备、IP会变,服务端这边留空即可,不用填。(这个字段一般是给"两个固定IP的服务器互联"场景用的,你这种手机/笔记本客户端场景不需要)

  1. 对端端口

同理,留空或者保持默认51820占位符不用管,服务端这边这个字段对客户端场景没意义,跳过。

  1. 持续保持连接(Persistent Keepalive)

填:

25 因为手机大概率处在NAT环境下(无论是WiFi还是4G/5G),这个值能防止连接因为长时间无流量被NAT设备判定断开。

  1. 保存后 —— 点"生成配置..."

这一步是重点:全部填完先点右下角"保存",保存完之后再进来点 配置导出 那个"生成配置..."按钮,系统会:

自动生成一份完整的客户端配置文件(包含私钥、服务端公钥、Endpoint地址等全部信息)

通常还会显示一个二维码

手机WireGuard App直接扫这个二维码就能一键导入配置,完全不用你手动输入任何字段,最省事。

  1. 填完这些保存之后,点"生成配置"
![alt text](https://cdn.tungchiahui.cn/tungwebsite/assets/images/2024/03/30/1783172425569.webp)

1. 连接端点 —— 改成DDNS域名
没有ddns域名的请看[ddns教程](/wiki/2024-03-30-linux-jiao-cheng/0900-qi-ta-cao-zuo#ddns).
现在显示的是 `112.233.39.5` 这个具体的公网IPv4,这是系统自动探测到的当前公网IP,但建议改成:`ddns.xxxxxx.cn`
原因很简单:家庭宽带的公网IP大概率是动态的(如果你是中国移动,你完全不需要担心这件事情,你没有公网ipv4,你只有公网ipv6),过一阵子运营商重新分配IP后,这个写死的IP就失效了,配置文件也就废了。用DDNS域名的话,只要你路由器上的DDNS客户端正常更新,域名自动跟着IP变化解析,配置文件永久有效,不用来回改。
直接把这个下拉框里的值改成 `ddns.tungchiahui.cn` 即可,如果下拉框里没有这个选项,看能不能手动输入替换。
2.  允许的IP —— 这个要看你的使用需求,建议改
现在是 0.0.0.0/0 + ::/0,意思是全局代理模式:连上VPN后,手机/电脑的所有上网流量(刷网页、看视频、聊天全部)都会先绕道回你家里,再从家里的网络出去上网。
这跟最初的需求("在外面访问家里NAS")不太一致,全局模式的影响:
✅ 优点:所有流量都通过加密隧道,公共WiFi环境下更安全
❌ 缺点:手机所有网络流量的速度都取决于你家宽带的上传带宽,如果你家是常见的百兆宽带(上传可能才几十M甚至更低),刷视频、下载会明显变慢;而且家里NAT要承担所有流量的转发压力
如果你只是想访问家里内网的NAS/PVE/Debian,建议改成分离隧道模式,把这两行改成:
10.10.10.0/24
10.0.0.0/24
删掉 0.0.0.0/0 和 ::/0 这两行(点它们右边的红色×号),只保留上面这两个网段。这样只有"访问家里内网"这一类流量才走VPN隧道,其他正常上网流量不受影响,速度不受影响。
如果你确实希望VPN也当"全局代理"用(比如出门用境外的WiFi想用家里的网络环境访问某些内容),那就保留 0.0.0.0/0 不用改。
3. DNS服务器:10.0.0.1 —— 这是你家庭内网的软路由的LAN地址,连VPN后用它解析域名没问题,能顺带解析你家内网可能配置的一些本地域名
4. 地址:10.10.10.2/32 —— 这个就是你想给你的这个手机分配一个VPN网段

alt text

然后掏出手机的客户端,使用QRcode导入配置即可.

alt text

服务端-防火墙设置

需要加的规则

去 网络 → 防火墙 → 通信规则(Traffic Rules),点"添加":

alt text

名称:WireGuard(随便起)

协议:UDP 或者 TCP/UDP

源区域:wan

目标区域:设备(输入) —— 因为WireGuard监听的是软路由本机端口,不是转发给内网其他设备

目标端口:51820(跟你wg0接口"监听端口"那里填的一致)

操作:接受(Accept)

alt text

保存,应用。

客户端

拿iOS举例子

我这里使用数据流量来测试,使用的是中国联通4G.

像使用普通的VPN一样打开你导入的这个配置即可.

alt text

test

然后可以尝试访问你的内网设备,

比如我的

openwrt是10.0.0.1,

pve是10.0.0.2,

nas是10.0.0.5都可以被正常访问了.

alt text

alt text

alt text

将WireGuard交由Clash Meta管理(可选)

将纯WireGuard配置放入Clash Meta

如果手机或电脑上已经长期运行支持Mihomo / Clash Meta内核的客户端,再单独启动WireGuard客户端会比较麻烦,而且同一台移动设备通常不能同时启用两个VPN隧道。

因此,可以将WireGuard节点直接写入Clash Meta配置,让Clash Meta统一负责:

  1. 普通互联网流量直连;
  1. 家庭内网流量通过WireGuard访问;
  1. 根据规则自动判断流量应该走哪个出口。

本节只介绍不包含机场或其他代理节点的纯WireGuard配置。

配置完成后,不再需要打开独立的WireGuard客户端。使用该配置时,应关闭WireGuard App中的隧道,只打开Clash Meta。

查看WireGuard客户端参数

先打开已经能够正常使用的WireGuard客户端配置,需要记录以下信息:

|Clash Meta字段|WireGuard客户端中的对应字段|

|:---|:---| |server|Peer中的Endpoint域名或公网IP|

|port|Peer中的Endpoint端口|

|ip|Interface中的Addresses,只填写IPv4地址,不写/32|

|private-key|Interface中的Private key|

|public-key|Peer中的Public key,也就是WireGuard服务器公钥|

|pre-shared-key|Peer中的Preshared key|

|persistent-keepalive|Peer中的Persistent keepalive|

这里最容易弄错的是两个公钥:

  • Interface中的Public key是当前客户端的公钥,不能填入Clash Meta的public-key
  • Peer中的Public key才是WireGuard服务器公钥,需要填入Clash Meta的public-key

建议截图中保留以下字段所在位置:

  • Interface:Private key、Public key、Addresses
  • Peer:Public key、Preshared key、Endpoint、Allowed IPs、Persistent keepalive

建议完全遮挡Private key和Preshared key;

客户端公钥、服务器公钥可只保留开头6~10位;

个人DDNS域名可替换为ddns.example.com。

-->

WireGuard客户端参数位置

这一张图同时包含Interface和Peer两部分,已经足够说明各个字段应该从哪里获取,不需要再增加其他截图。

创建YAML配置

新建一个扩展名为.yaml的文件,例如:

home-wireguard.yaml

写入下面的模板:

# 仅让家庭内网流量通过WireGuard
# 普通互联网流量保持直连
# 启用本配置时,不要同时开启独立的WireGuard客户端

mixed-port: 7890
allow-lan: false
mode: rule
log-level: info
ipv6: true

tun:
  enable: true
  stack: mixed
  auto-route: true
  auto-detect-interface: true

proxies:
  - name: 家庭-WG
    type: wireguard

    # WireGuard客户端Peer中的Endpoint
    server: ddns.example.com
    port: 51820

    # WireGuard客户端Interface中的Addresses
    # 例如原配置为10.10.10.2/32,这里只填写10.10.10.2
    ip: 10.10.10.2

    # WireGuard客户端Interface中的Private key
    private-key: "gBzeTbZH..."

    # WireGuard客户端Peer中的Public key,即服务器公钥
    # 不要填写Interface中的客户端公钥
    public-key: "UUS0nrKE..."

    # WireGuard客户端Peer中的Preshared key
    pre-shared-key: "NGYvFsCle..."

    allowed-ips:
      - 0.0.0.0/0

    udp: true
    persistent-keepalive: 25
    mtu: 1380

rules:
  # 家庭局域网网段
  - IP-CIDR,10.0.0.0/24,家庭-WG,no-resolve

  # WireGuard隧道网段
  - IP-CIDR,10.10.10.0/24,家庭-WG,no-resolve

  # 其他网络流量保持直连
  - MATCH,DIRECT
修改模板中的参数

需要按照自己的WireGuard配置修改以下内容。

1. server

将:

server: ddns.example.com

改成WireGuard客户端Peer中Endpoint冒号前面的域名或公网IP。

例如Endpoint为:

ddns.example.com:51820

那么填写:

server: ddns.example.com

2. port

填写Endpoint冒号后面的端口,例如:

port: 51820

3. ip

填写WireGuard客户端Interface中的Addresses,但不要填写CIDR后缀。

例如原配置是:

10.10.10.2/32

Clash Meta中填写:

ip: 10.10.10.2

4. private-key

填写WireGuard客户端Interface中的Private key:

private-key: "客户端私钥"

5. public-key

填写WireGuard客户端Peer中的Public key,也就是服务器公钥:

public-key: "服务器公钥"

不要误填Interface中的Public key。Interface中的Public key属于当前客户端,Peer中的Public key才属于服务器。

6. pre-shared-key

填写WireGuard客户端Peer中的Preshared key:

pre-shared-key: "预共享密钥"

WireGuard密钥是Base64字符串,复制时不要漏掉末尾可能存在的=

7. rules

将规则中的家庭局域网网段和WireGuard隧道网段改成自己的实际网段。

For example:

rules:
  - IP-CIDR,10.0.0.0/24,家庭-WG,no-resolve
  - IP-CIDR,10.10.10.0/24,家庭-WG,no-resolve
  - MATCH,DIRECT

Indicates:

  • 访问10.0.0.0/24家庭局域网时走WireGuard;
  • 访问10.10.10.0/24WireGuard隧道网段时走WireGuard;
  • 其他流量全部直连,不经过家庭宽带。
关于allowed-ips

模板中的:

allowed-ips:
  - 0.0.0.0/0

可以保持不变。

它表示这个WireGuard代理节点能够承载全部IPv4流量,但实际哪些流量交给WireGuard,仍然由最下面的rules决定。

For example:

rules:
  - IP-CIDR,10.0.0.0/24,家庭-WG,no-resolve
  - IP-CIDR,10.10.10.0/24,家庭-WG,no-resolve
  - MATCH,DIRECT

在这套规则下,只有家庭内网和WireGuard隧道网段走WireGuard,其他互联网流量继续直连。

需要注意,WireGuard服务端Peer中的Allowed IPs仍然应该是分配给该客户端的地址,例如:

10.10.10.2/32

不要把WireGuard服务端Peer中的Allowed IPs改成0.0.0.0/0

导入并测试

将YAML文件导入支持Mihomo / Clash Meta内核的客户端,然后:

  1. 关闭独立的WireGuard客户端隧道;
  1. 在Clash Meta中选择刚才导入的配置;
  1. 使用“规则”模式;
  1. 打开Clash Meta连接开关;
  1. 访问家庭内网设备进行测试。

例如访问软路由:

http://10.0.0.1

或者在iOS文件App中连接NAS:

smb://10.0.0.5

同时可以进入WireGuard服务端,查看对应Peer的Latest Handshake。

如果开启Clash Meta后握手时间刷新,并且能够访问家庭内网设备,就说明配置成功。

Frequently Asked Questions

如果YAML能够启动,但无法产生WireGuard握手,优先检查:

  1. public-key是否误填成客户端公钥;
  1. private-key是否为当前客户端私钥;
  1. pre-shared-key是否完整,末尾的=是否遗漏;
  1. ip是否与服务端分配给该Peer的地址一致;
  1. Endpoint域名和端口是否正确;
  1. 软路由防火墙是否已经放行WireGuard端口;
  1. 独立WireGuard客户端是否仍然处于开启状态。

如果报错类似:

decode pre shared key: illegal base64 data

通常说明pre-shared-key复制不完整,常见原因是末尾的=被遗漏。

将WireGuard加入包含代理节点的YAML
音乐页