如何使用sed替换qBittorrent配置文件中的SSL证书/密钥值?
Got it, let's tackle how to replace the SSL certificate and private key in qBittorrent's config file using sed. The tricky part here is handling the multi-line content inside the @ByteArray(...) blocks—so we need to make sure sed correctly targets and replaces those entire blocks without breaking the config format.
Step 1: Prepare Your New Cert/Key Files
First, save your updated certificate and private key into separate files (e.g., new_cert.pem and new_key.pem). Make sure these files include the full -----BEGIN CERTIFICATE-----/-----END CERTIFICATE----- and -----BEGIN PRIVATE KEY-----/-----END PRIVATE KEY----- headers/footers—qBittorrent expects these to be present.
Step 2: Replace the Certificate
Use this sed command to replace the existing certificate block in your qBittorrent config (usually named qBittorrent.conf):
# First, backup your config (always a good idea!) cp qBittorrent.conf qBittorrent.conf.bak # Replace the certificate sed -i '/WebUI\\HTTPS\\Certificate=@ByteArray(/,/-----END CERTIFICATE-----)/c\WebUI\\HTTPS\\Certificate=@ByteArray('"$(cat new_cert.pem | sed 's/\\/\\\\/g; s/"/\\"/g')"')' qBittorrent.conf
Breakdown of the command:
/WebUI\\HTTPS\\Certificate=@ByteArray(/,/-----END CERTIFICATE-----)/: This targets the entire range of lines starting with the certificate's@ByteArray(opening, all the way to the-----END CERTIFICATE-----)closing.c\: Tellssedto replace the matched range with the new content we specify.$(cat new_cert.pem | sed 's/\\/\\\\/g; s/"/\\"/g'): Reads your new certificate file, and escapes any backslashes (\→\\) and double quotes ("→\") to ensure they don't break the config's syntax.
Step 3: Replace the Private Key
Similarly, use this command to replace the private key block:
sed -i '/WebUI\\HTTPS\\Key="@ByteArray(/,/-----END PRIVATE KEY-----)/c\WebUI\\HTTPS\\Key="@ByteArray('"$(cat new_key.pem | sed 's/\\/\\\\/g; s/"/\\"/g')"')"' qBittorrent.conf
Note the extra double quote at the start of the key line (Key="@ByteArray()—we make sure to include that in both the match pattern and the replacement to keep the config format correct.
Important Notes
- Restart qBittorrent: After replacing the cert/key, you'll need to restart qBittorrent for the changes to take effect.
- Windows Users: If you're on Windows, use a Unix-like shell like Git Bash or WSL to run these commands—native Windows
sedhas different syntax and may not handle multi-line matches correctly. - Verify the Config: After running the commands, open
qBittorrent.confto double-check that the new cert/key are properly inserted and there are no syntax errors (like missing closing parentheses or unescaped characters).
内容的提问来源于stack exchange,提问作者tyros

