在 Ubuntu 上使用 clash 代理工具

我是今年才开始尝试使用 Ubuntu 作为业余时间的开发,上班的时候还是用 Mac。现在 freelancer 了,Ubuntu 成为了主力开发机。相比 Mac,用 Ubuntu 最大的遗憾就是有很多 Mac 上的软件无法享用了,比如 Alfred,还比如代理工具 Surge

我一直在尝试寻找 Surge 的替代品。比如我用了 clashx 一段时间,问题不少,最终还是放弃了。

最后还是采用了 clash 的方案,不过不用任何桌面端了。下面是 clash 的安装步骤(参考这里):

# 创建安装目录
mkdir ~/.config/clash

# 下载 clash 配置文件
# 订阅地质是代理服务商提供的
wget --no-check-certificate -O ~/.config/clash/config.yaml 订阅地址

# 下载 GeoIP 库
wget --no-check-certificate -O ~/.config/clash/Country.mmdb https://whiter.cc/cached-apps/linux/Country.mmdb

# 下载 clash 主程序
# 我一般喜欢用源码自己构建
# clash 是用 golang 写的,构建前提前安装好 golang
git clone git@github.com:Dreamacro/clash.git
cd clash/
go build

# 构建成功的话,会得到一个 clash 可执行文件
# 直接把可执行文件软链到 /usr/bin/ 目录下
sudo ln -s ~/.config/clash/clash/clash /usr/bin/clash

# 运行 clash
clash

这时的 clash 还是前台运行,还要把它设置成自动启动的后台进程,最好还要自动更新订阅地址的配置,参考了这里的代码

# 在 /lib/systemd/ 目录创建 clash 服务
sudo vim /lib/systemd/clash.service

# 服务的内容
[Unit]
Description=clash
After=network.target

[Service]
WorkingDirectory="your home directory"/.config/clash
ExecStart="your home directory"/.config/clash/start-clash.sh
ExecStop="your home directory"/.config/clash/stop-clash.sh
Environment="HOME=your home directory"
Environment="CLASH_URL=your subscribe address"

RestartSec=1
Restart=on-failure

StandardOutput=syslog
StandardError=syslog

SyslogIdentifier=clash

[Install]
WantedBy=multi-user.target

上面定义了一个启动脚本 start-clash.sh 和一个终止脚本 stop-clash.sh,还得创建以下

#!/bin/bash
# save this file to ${HOME}/.config/clash/start-clash.sh

# save pid file
echo $$ > ${HOME}/.config/clash/clash.pid

diff ${HOME}/.config/clash/config.yaml <(curl -s ${CLASH_URL})
if [ "$?" == 0 ]
then
    /usr/bin/clash
else
    TIME=`date '+%Y-%m-%d %H:%M:%S'`
    cp ${HOME}/.config/clash/config.yaml "${HOME}/.config/clash/config.yaml.bak${TIME}"
    curl -L -o ${HOME}/.config/clash/config.yaml ${CLASH_URL}
    /usr/bin/clash
fi
#!/bin/bash
# save this file to ${HOME}/.config/clash/stop-clash.sh

# read pid file
PID=`cat ${HOME}/.config/clash/clash.pid`
kill -9 ${PID}
rm ${HOME}/.config/clash/clash.pid

定义完之后就可以启动程序了。

systemctl enable clash
systemctl start clash

查看运行情况

systemctl status clash

然后就可以在 Ubuntu 的配置里把代理地址填上(Settings -> Network -> Network Proxy -> Manual),Socks Host 填 127.0.0.1:8889,其他 Host 填 127.0.0.1:8888

大功告成。

另外比较蛋疼的是 Ubuntu 的 Chrome 似乎无法默认使用系统的 proxy,还是得装个插件。

· tech, ubuntu