使用 sed 替换 Apache 虚拟主机文件中的 SSL 证书

Replace SSL certificate in Apache vhosts-file using sed

我有一个 cron 作业脱水运行以更新我的 QNAP 网络服务器上的 Let's Encrypt 证书。

我希望它获取 QNAP 生成的当前 vhosts 文件,获取实际站点的部分,然后用正确的证书数据替换该信息。

这是虚拟主机文件的一部分:

<VirtualHost *:443>
<Directory "/share/Web/domains">
    Options FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>
    ServerName www.example.com
    DocumentRoot "/share/Web/domains"
    SSLEngine on
    SSLCipherSuite EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5
    SSLProtocol All -SSLv2 -SSLv3
    SSLCertificateChainFile "/etc/stunnel/uca.pem"
    SSLCertificateFile "/etc/stunnel/stunnel.pem"
</VirtualHost>
<VirtualHost *:443>
<Directory "/share/Web/someotherdir">
    Options FollowSymLinks MultiViews
    AllowOverride All
    Require all granted
</Directory>
    ServerName www.anotherexample.com
    DocumentRoot "/share/Web/someotherdir"
    SSLEngine on
    SSLCipherSuite EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5
    SSLProtocol All -SSLv2 -SSLv3
    SSLCertificateChainFile "/etc/stunnel/uca.pem"
    SSLCertificateFile "/etc/stunnel/stunnel.pem"
</VirtualHost>

使用这个文件,我已经设法将一个小命令放在一起用新信息替换它:

unchanged_cert() {
local DOMAIN="" KEYFILE="" CERTFILE="" FULLCHAINFILE="" CHAINFILE=""

# This hook is called once for each certificate that is still
# valid and therefore wasn't reissued.
#
# Parameters:
# - DOMAIN
#   The primary domain name, i.e. the certificate common
#   name (CN).
# - KEYFILE
#   The path of the file containing the private key.
# - CERTFILE
#   The path of the file containing the signed certificate.
# - FULLCHAINFILE
#   The path of the file containing the full certificate chain.
# - CHAINFILE
#   The path of the file containing the intermediate certificate(s).

#Prepare new values
lead='ServerName '${DOMAIN}'$'
tail='^<\/VirtualHost>$'
insert='\ \       SSLEngine on \
    SSLCipherSuite EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:!MD5 \
    SSLProtocol All -SSLv2 -SSLv3 \
    SSLCertificateChainFile "'${FULLCHAINFILE}'" \
    SSLCertificateKeyFile "'${KEYFILE}'" \
    SSLCertificateFile "'${CERTFILE}'"'

#Insert new values to VHOSTS-file
#NOTE: command must be on 2 lines
sed -e "/$lead/,/$tail/{ /$lead/{p; i $insert
}; /$tail/p; d }" --in-place /etc/config/apache/extra/httpd-ssl-vhosts-user.conf
}

有效,它删除了 DocumentRoot“/share/Web/domains” 行,这对服务器操作至关重要. 我不太擅长 sed,但我希望有一种方法可以忽略删除这一行。我就是想不通。

有人可以指导我正确的方向吗?由于服务器托管多个域,我不能像其他变量一样对其进行硬编码。

试试这个:

sed -i "/$lead/,/$tail/{/SSL/d};/DocumentRoot/a$insert" /etc/config/apache/extra/httpd-ssl-vhosts-user.conf

先删除 SSL 行,然后在 DocumentRoot 行后附加插入文本。