安装certbot
mkdir -p /data/certbot #创建certbot工作目录
cd /data/certbot
python -m venv venv #在certbot目录创建python工作环境,注意需要Python 3.7或以上版本支持
source venv/bin/activate #执行python工作环境下的activate命令,source只是Linux执行命令的一种方式,和直接用 ./venv/bin/activate执行时一样的
用source执行脚本文件,执行过程不另开进程,脚本文件中设定的变量在当前shell中可以看到;
用sh执行脚本文件,是在当前进程另开子进程来执行脚本命令,脚本文件中设定的变量在当前shell中不能看到。
pip install certbot certbot-nginx certbot-dns-aliyun #在当前python工作环境中安装 certbot和阿里云dns插件
ln -sf /data/certbot/venv/bin/certbot /usr/bin/certbot #创建软链,以便可以直接执行certbot
如果执行certbot 提示: ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with OpenSSL 1.0.2k-fips 26 Jan 2017. See: https://github.com/urllib3/urllib3/issues/2168
说明urllib3版本太高,可以降低urllib3版本:
pip uninstall urllib3
pip install 'urllib3<2.0'
然后重新安装
pip uninstall certbot certbot-nginx certbot-dns-aliyun
pip install certbot certbot-nginx certbot-dns-aliyun
为nginx添加证书并自动修改nginx配置
certbot --nginx
如果Nginx配置文件不在/etc/nginx/nginx.conf目录,则需要指定目录
certbot --nginx --nginx-server-root=/usr/local/nginx/conf (等号右边填写nginx配置文件的目录)
为nginx添加证书
certbot certonly --nginx
测试证书更新
certbot renew --dry-run
证书更新
certbot renew
阿里云泛域名证书
Certbot 支持自动申请 LetsEncrypt 的泛域名证书,但是官方插件不支持阿里云,在 GitHub 搜索发现已经有人写好了阿里云 DNS 插件,下面只需要进行简单的配置即可免费申请一个泛域名证书并自动续订。
申请并配置阿里云 DNS 访问密钥
前往 https://ram.console.aliyun.com 申请阿里云子账号并授予 AliyunDNSFullAccess 权限。然后为子账号创建 AccessKey 并记录。
创建 certbot-dns-aliyun 配置文件:
cat > /data/certbot/credentials.ini <<EOF
certbot_dns_aliyun:dns_aliyun_access_key = 12345678
certbot_dns_aliyun:dns_aliyun_access_key_secret = 1234567890abcdef1234567890abcdef
EOF
修改文件权限
chmod 600 /data/certbot/credentials.ini
创建证书
/data/certbot/venv/bin/certbot \
-a certbot-dns-aliyun:dns-aliyun \
--certbot-dns-aliyun:dns-aliyun-credentials \
/data/certbot/credentials.ini \
-d xxx.com \
-d "*.xxx.com" \
--nginx-server-root=/usr/local/nginx/conf
如果提示:certbot: error: unrecognized arguments: --certbot-dns-aliyun:dns-aliyun-credentials /data/certbot/credentials.ini
cat > /data/certbot/credentials.ini <<EOF
dns_aliyun_access_key = 12345678
dns_aliyun_access_key_secret = 1234567890abcdef1234567890abcdef
EOF
/data/certbot/venv/bin/certbot \
-a dns-aliyun \
--dns-aliyun-credentials \
/data/certbot/credentials.ini \
-d xxx.com \
-d "*.xxx.com" \
--nginx-server-root=/usr/local/nginx/conf
配置crontab自动更新
43 0 * * * certbot renew -q > /dev/null
非阿里云,直接使用certbot-nginx,但该方式不支持泛域名
mkdir -p /data/certbot #创建certbot工作目录
cd /data/certbot
python -m venv venv #在certbot目录创建python工作环境
source venv/bin/activate #执行python工作环境下的activate命令,source只是Linux执行命令的一种方式,和直接用 ./venv/bin/activate执行时一样的
pip install certbot certbot-nginx
ln -sf /data/certbot/venv/bin/certbot /usr/bin/certbot #创建软链,以便可以直接执行certbot
申请和安装证书
certbot --nginx --nginx-server-root=/usr/local/nginx/conf
配置crontab自动更新
43 0 * * * certbot renew -q > /dev/null