TL;DR
Creating temporary SSH key pairs adds a layer of security by limiting the lifespan of credentials used to connect to remote servers. This reduces the risk if a key is compromised. Here’s how to do it.
Generating Temporary SSH Keys
- Check for ssh-keygen: Most Linux and macOS systems have this tool pre-installed. Open your terminal and type:
ssh-keygen -t rsaIf it’s not found, you may need to install the OpenSSH client package (e.g.,
sudo apt install openssh-clienton Debian/Ubuntu). - Generate a key with a short validity: Use the
-foption to specify a filename and the-t rsaoption for RSA keys. The important part is using the-vflag to set a validity period.ssh-keygen -t rsa -f ~/.ssh/temp_key -N "" -v +1hThis creates a key named
temp_keyin your.sshdirectory that will expire after one hour (+1h). The-N ""part sets an empty passphrase (for simplicity, but consider using a passphrase for increased security). - Set appropriate permissions: Ensure the key file has restricted access.
chmod 600 ~/.ssh/temp_key - Connect to the server: Use the generated key when connecting with SSH.
ssh -i ~/.ssh/temp_key user@server_addressReplace
userandserver_addresswith your actual username and server address. - Verify connection: Once connected, confirm you’re using the temporary key (e.g., by checking authorized keys on the server).
- Key Expiration & Automatic Removal (Optional): The key will automatically become unusable after its validity period expires. You can also manually remove it:
rm ~/.ssh/temp_key
Benefits of Temporary Keys
- Reduced Attack Window: If a key is compromised, the attacker has limited time to use it.
- Improved Security Posture: Encourages good security practices by avoiding long-lived credentials.
- Automation Friendly: Easily scriptable for automated tasks requiring temporary access.
Important Considerations
- Passphrases: While the example uses an empty passphrase, always consider using a strong passphrase to protect your key even during its short lifespan.
- Key Management: Keep track of generated keys and their expiration times.
- Authorized Keys: Be careful when adding temporary keys to
authorized_keysfiles on servers. Consider automated management tools for larger deployments.

