前言

最近GPT比较火,考虑使用api进行后续应用的对接,目前国内服务器不能直接访问「api.openai.com」,所以尝试使用代理进行访问。

Clash 部署

部署

1、首先到github下载代理工具,选择对应的版本,地址传送门>

ubuntu一般使用clash-linux-amd64版本

可以使用命令:

wget https://github.com/Dreamacro/clash/releases/download/v1.14.0/clash-linux-amd64-v1.14.0.gz

2、下载后进行解压,并重命名为clash

gunzip clash-linux-amd64-v1.14.0.gz
mv clash-linux-amd64-v1.14.0 /usr/local/bin/clash

3、为clash添加可执行权限

chmod u+x clash

4、执行 ./clash 下载配置文件
第一次运行,会下载文件:Country.mmdb、config.yaml、clash.db

也可以手动下载Country.mmdb:https://github.com/Dreamacro/maxmind-geoip/releases
下载默认目录为 /home/{user}/.config/clash

5、运行
运行./clash 命令出现如下提示则表示成功:

INFO[0000] Mixed(http+socks) proxy listening at: [::]:7890
INFO[0000] RESTful API listening at: 127.0.0.1:9090

此时还没配置相关代理规则,只是clash安装成功并启动


配置代理

1、需要你已经有了相关的VPN代理服务配置,一般网络服务提供了Clash的订阅链接,可以直接下载指定内容,使用如下命令:

wget -O /home/{user}/.config/clash/config.yaml [你的订阅链接]

问题:在使用时下载的内容为一长串字符串,非yaml的配置,应该是订阅格式不同
解决方式:通过本地的Clash导入订阅地址,拿到对应的yaml,进行copy完成。

2、设置系统代理
创建文件:/etc/profile.d/proxy.sh,写入如下内容:

export http_proxy="127.0.0.1:7890"
export https_proxy="127.0.0.1:7890"
export no_proxy="localhost, 127.0.0.1"

配置表示HTTP 和 HTTPS 请求会通过 http_proxy 和 https_proxy 指定的代理服务器发送,而对于本地主机和局域网中的其它服务器,请求则会直接发送,不经过代理服务器。


使生效:

source /etc/profile

临时取消系统代理,执行如下命令:unset http_proxy https_proxy no_proxy


验证系统代理是否生效,执行如下命令:
$ env | grep -E ‘http_proxy|https_proxy’

http_proxy=http://127.0.0.1:7890
https_proxy=http://127.0.0.1:7890

变成系统服务

1、创建脚本文件:/etc/systemd/system/clash.service

[Unit]
Description=clash daemon
[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/clash -d /home/{user}/.config/clash
Restart=on-failure
[Install]
WantedBy=multi-user.target

/usr/local/bin/clash 指定clash命令
-d /home/{user}/.config/clash 指定了配置文件目录

2、重载 systemctl daemon

systemctl daemon-reload

如果变动脚本,也需要执行重载,然后再重启服务,否则会有如下警告:
Warning: The unit file, source configuration file or drop-ins of clash.service changed on disk. Run ‘systemctl daemon-reload’ to reload units.

3、启动
使用如下命令

开机自启动:systemctl enable clash
启动:systemctl start clash
重启:systemctl restart clash
关闭:systemctl stop clash

查看日志:journalctl -xe

查看启动状态:执行如下命令:systemctl status clash
image-1681314667819

验证

执行如下命令:curl google.com 出现如下,则表示成功。

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

访问 api.openai

执行 curl api.openai.com 无法成功
修改代理规则:/home/{user}/.config/clash/config.yaml
添加配置(照猫画虎):
- ‘DOMAIN-SUFFIX,openai.com,BH专线版’
- ‘DOMAIN-SUFFIX,api.openai.com,BH专线版’

配置完成后,执行如下命令:curl api.openai.com,出现如下,则表示成功。

{
  "error": {
    "message": "The OpenAI API can only be accessed over HTTPS. You should access https://api.openai.com rather than the current URL.",
    "type": "invalid_request_error"
  }
}


总结

1、成功通过Clash完成Ubuntu服务器的代理,在应用程序中使用时指定代理127.0.0.1:7890即可。
2、代理前提需要有个订阅地址,一般获取账号的地方「机场」都会提供, 也就是VPN提供商。