2025-10-22    2025-10-22    866 字  2 分钟

The note is generated by chatGPT.

🌟 在 Linux 服务器上用 root 配置 Clash 服务


🪶 1. 创建目录并放置文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
sudo mkdir -p /opt/mihomo
cd /opt/mihomo


将clash for linux的相关文件移动到/opt/mihomo:
/opt/mihomo/
├── clash-linux        # 主程序(可执行文件)
├── config.yaml        # 配置文件
├── Country.mmdb       # 国家数据库
├── GeoIP.dat          # IP 地理数据库
├── GeoSite.dat        # 网站分类数据库
├── cache.db           # 可选缓存文件

设置权限(root 拥有,程序可执行):

1
2
sudo chmod +x /opt/mihomo/clash-linux
sudo chown -R root:root /opt/mihomo

⚙️ 2. 创建 systemd 服务

新建服务文件:

1
sudo vim /etc/systemd/system/clash.service

写入以下内容:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
[Unit]
Description=Mihomo (Clash) Proxy Service

After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/mihomo
ExecStart=/opt/mihomo/clash-linux -d /opt/mihomo
Restart=on-failure
RestartSec=3
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

🔄 3. 启用并启动服务

1
2
3
sudo systemctl daemon-reload
sudo systemctl enable clash
sudo systemctl start clash

查看运行状态:

1
sudo systemctl status clash

出现 “active (running)” 表示启动成功 ✅


📜 4. 常用管理命令

操作命令
启动服务sudo systemctl start clash
停止服务sudo systemctl stop clash
重启服务sudo systemctl restart clash
查看状态sudo systemctl status clash
查看日志sudo journalctl -u clash -f

🌐 5. 验证代理是否正常

1
curl -x http://127.0.0.1:7890 https://www.google.com -I

若返回 HTTP/2 200HTTP/1.1 200 OK,说明代理正常工作。

查看端口监听:

1
sudo netstat -tunlp | grep clash

⚡ 6. (可选)全局代理命令工具

可在 /etc/profile.d/proxy-control.sh 中添加以下脚本,让所有用户通过命令控制代理:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 开启代理
proxy_on() {
    export ALL_PROXY="http://127.0.0.1:7890"
    export HTTP_PROXY="http://127.0.0.1:7890"
    export HTTPS_PROXY="http://127.0.0.1:7890"
    export http_proxy="http://127.0.0.1:7890"
    export https_proxy="http://127.0.0.1:7890"
    echo "🔓 代理已开启"
}

# 关闭代理
proxy_off() {
    unset ALL_PROXY HTTP_PROXY HTTPS_PROXY http_proxy https_proxy
    echo "🔒 代理已关闭"
}

# 查看代理状态
proxy_status() {
    if [ -n "$ALL_PROXY" ]; then
        echo "🟢 代理状态: 开启 ($ALL_PROXY)"
    else
        echo "🔴 代理状态: 关闭"
    fi
}

# 测试代理连通性
proxy_test() {
    echo "🧪 测试代理连接..."
    if curl -s --connect-timeout 10 -I https://www.google.com > /dev/null; then
        echo "✅ 代理连接成功"
    else
        echo "❌ 代理连接失败"
    fi
}

让所有终端(包括 VS Code)都能使用这些命令:

1
echo 'source /etc/profile.d/proxy-control.sh' | sudo tee -a /etc/bash.bashrc

✅ 7. 验证服务自动启动

重启服务器后,执行:

1
sudo systemctl status clash

如果状态为 active (running),说明 Clash/Mihomo 已设置为开机自启成功。


🧠 总结

目标操作
程序与配置统一放置/opt/mihomo/
运行用户root
服务管理systemd
开机自动启动sudo systemctl enable clash
全局代理控制/etc/profile.d/proxy-control.sh
推荐用途服务器全局代理、内网共享、生产环境部署

💡 建议将 /opt/mihomo/config.yaml 版本控制(如 Git 或手动备份),以便在更换节点或配置时快速恢复。