如何在脚本中为无密码SSH私钥设置非空密码
Great question! Let's break this down clearly:
No, it’s not. Here’s why:
- The
ssh-keygen -pcommand requires two identical passphrase inputs (once to set it, once to confirm). Your command only pipes the password once, so it’ll hang waiting for the confirmation input and ultimately fail to set the passphrase. - Passing the password as plaintext in a piped command is a major security risk: it’ll show up in your shell history, be visible via tools like
pswhile the command runs, and could be logged by system monitoring tools.
Let’s cover the most common and safe methods to add a passphrase to an unencrypted SSH key:
1. Interactive (Recommended, Most Secure)
This is the simplest and safest way—just run the command without piping input, and follow the prompts:
ssh-keygen -p -f ~/.ssh/id_rsa
You’ll see:
Enter new passphrase:
Enter same passphrase again:
Type your desired passphrase twice (it won’t be displayed on screen), and you’re done. No plaintext exposure, no shell history risks.
2. Non-Interactive (For Scripts, But Use Carefully)
If you need to automate this in a script, avoid plaintext command-line inputs. Instead, use one of these safer options:
Option A: Use read to capture the passphrase (semi-interactive)
This lets you input the passphrase securely without it appearing in the terminal:
read -sp "Enter new SSH passphrase: " NEW_PASS && echo && \ echo -e "$NEW_PASS\n$NEW_PASS" | ssh-keygen -p -f ~/.ssh/id_rsa
The -s flag hides the input, so your passphrase stays private.
Option B: Use a secured temporary file
If you must predefine the passphrase (not ideal, but sometimes necessary for automation), store it in a temporary file with strict permissions first:
# Create a temp file with read/write only for your user echo -e "your_secure_passphrase\nyour_secure_passphrase" > /tmp/ssh_pass.tmp chmod 600 /tmp/ssh_pass.tmp # Use the file to set the passphrase ssh-keygen -p -f ~/.ssh/id_rsa < /tmp/ssh_pass.tmp # Delete the temp file immediately to clean up rm /tmp/ssh_pass.tmp
Never leave the passphrase file lying around, and always set chmod 600 to prevent other users from reading it.
After updating your private key, double-check its file permissions—SSH will reject private keys that are readable by other users:
chmod 600 ~/.ssh/id_rsa
内容的提问来源于stack exchange,提问作者Marci-man

