You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在脚本中为无密码SSH私钥设置非空密码

Great question! Let's break this down clearly:

Is your current command correct?

No, it’s not. Here’s why:

  • The ssh-keygen -p command 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 ps while the command runs, and could be logged by system monitoring tools.
Better, more secure approaches

Let’s cover the most common and safe methods to add a passphrase to an unencrypted SSH key:

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.

Critical Post-Step

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:08:45