VPS Tutorials
Set up SSH key authentication on a VPS: safe rollout and recovery
Generate and install SSH keys, verify a genuinely fresh login, check OpenSSH configuration precedence and disable unwanted password paths. Manage agents, Windows clients, revocation and recovery without locking yourself out.

Public SSH services receive automated login attempts. If your provider supplies an initial password, use it only through a verified connection while establishing your own access. Logs may appear in /var/log/auth.log or the system journal, depending on the image.
Public-key authentication makes password guessing ineffective against a key-only login, but does not prevent stolen keys, abused agents or a compromised server. The most important operational rule is to keep a working session and tested console access until a fresh connection proves the new configuration works.
- Keep the private key on a trusted client or protected signing device; never upload it to the VPS or send it to another person.
- Install the public key for the intended server account. It is not secret, but its ownership and authenticity still matter.
- SSH proves possession through a signature; the private key itself is not transmitted.
| Consideration | Password | Public key |
|---|---|---|
| Online guessing | Depends on strength and rate controls | Practical password guessing does not recover a modern key |
| Reuse | Leaked reused passwords affect multiple accounts | A stolen key affects every account that authorizes it |
| Automation | Requires a protected credential mechanism | Requires a protected key/agent and suitable restrictions |
| Server compromise | Hashes such as /etc/shadow may enable offline attacks | Does not normally reveal a client-only private key, but the compromised server is still untrusted |
Run this on your own computer, not the VPS:
ssh-keygen -t ed25519 -C "[email protected]"
Check the destination before accepting defaults so you do not overwrite an existing key. The private file is ~/.ssh/id_ed25519, without .pub; the public file is ~/.ssh/id_ed25519.pub.
Ed25519 has been supported since OpenSSH 6.5 in 2014 and is a useful modern default when policy permits. The commonly cited 68 characters describe the encoded public-key blob, not the whole authorized_keys line. FIPS policies and older equipment may require another supported algorithm.
ssh-keygen -t rsa -b 4096 -C "[email protected]"
Use RSA with modern SHA-256/512 signatures where required. OpenSSH 8.8 disabled the SHA-1 ssh-rsa signature by default, not RSA keys themselves. Historical SHA-1 chosen-prefix collision estimates below US$50,000 concern that research, not a current price for breaking an SSH private key; do not globally re-enable obsolete signatures to fix one old device.
At Enter passphrase, choose a strong passphrase for a personal key. It protects a stolen encrypted file, though not an already unlocked compromised client. Use ssh-agent or a suitable hardware-backed workflow to reduce repeated prompts. Unattended keys need a separately reviewed, restricted design.
The -C comment is just a label. The original 工作本-2026 illustrates a workstation label; choose something meaningful such as work-laptop-2026.
Replace the original IP placeholders and root account with the real host and intended account in all following examples. Verify its host-key fingerprint through a trusted provider/console before supplying credentials.
ssh-copy-id -i ~/.ssh/id_ed25519.pub root@你的服务器IP
ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 root@你的服务器IP
The second command is the alternative for port 2222. ssh-copy-id normally needs an already authorized login and appends the public key to ~/.ssh/authorized_keys.
If that tool is unavailable, create the directory/file for the intended account on the server:
mkdir -p ~/.ssh && chmod 700 ~/.ssh
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... [email protected]" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
Obtain the complete public line locally with cat ~/.ssh/id_ed25519.pub. Use the .pub file, not the private one, and replace the truncated sample. Provider key injection is another option, but check whether it applies only at creation/rebuild or updates an existing instance.
chmod 700 ~/.ssh # 只有你能进这个目录
chmod 600 ~/.ssh/authorized_keys # 只有你能读写
chmod 600 ~/.ssh/id_ed25519 # 本地私钥
chmod 644 ~/.ssh/id_ed25519.pub # 公钥无所谓
Apply server directory/authorized-key permissions on the server; private/public key-file lines belong on the local client. Use the intended account's ownership. StrictModes protects authentication files against unauthorized modification; it is not checking for a client private key on the server.
ls -ld ~
# 应该是 drwxr-xr-x,不能是 drwxrwxrwx
chmod g-w,o-w ~
A home directory need not be exactly 755, but must satisfy ownership and writability checks. 777 lets other users modify paths such as ~/.ssh and can make SSH reject authorization. On native Windows, inspect NTFS ACLs; Unix chmod alone is not its permission model.
Keep the current connection open and test in another terminal:
ssh -i ~/.ssh/id_ed25519 root@你的服务器IP
# 想看详细的连接过程,加上 -v
ssh -v -i ~/.ssh/id_ed25519 root@你的服务器IP
Offering public key and Server accepts key show intermediate progress. Confirm the final authentication uses publickey. A password fallback or reused multiplexed connection can give a false impression of success. For a dedicated test:
ssh -o ControlPath=none -o IdentitiesOnly=yes \
-o PreferredAuthentications=publickey \
-o PasswordAuthentication=no -o KbdInteractiveAuthentication=no \
-i ~/.ssh/id_ed25519 user@HOST
Replace user/HOST and include the actual port. If it fails, repair key content, account, ownership and effective settings while the original session still works.
Back up configuration, including any include files you will edit:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F)
sudo sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?KbdInteractiveAuthentication.*/KbdInteractiveAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?ChallengeResponseAuthentication.*/ChallengeResponseAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/^#\?PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config
The sed examples change only existing matching lines in one file; they do not guarantee effective policy. To make SSH key-only, review KbdInteractiveAuthentication as well as PasswordAuthentication no: keyboard-interactive/PAM may offer a separate password path from PasswordAuthentication. Do not assume Ubuntu always enables it. If an intentional MFA policy uses keyboard-interactive, review that design rather than disabling it blindly.
# 允许 root 用密钥登录,但禁止用密码(推荐)
sudo sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
PermitRootLogin prohibit-password permits authorized root keys; no disables direct root login. A separate tested sudo account is usually easier to audit. Choose the recovery policy deliberately.
grep -r "PasswordAuthentication\|PermitRootLogin" /etc/ssh/sshd_config.d/ 2>/dev/null
Files under /etc/ssh/sshd_config.d/ can set values before the main file reaches later lines. If 50-cloud-init.conf sets PasswordAuthentication yes, a later no does not automatically replace it.
Include /etc/ssh/sshd_config.d/*.conf
OpenSSH normally uses the first obtained value for a keyword within the applicable context, not the last. The position of Include / Include and lexical ordering of files in sshd_config.d/ matter. A file named 99-custom.conf loading last is therefore not a reliable override. Edit the actual controlling setting or use a deliberately earlier file after inspecting existing settings and Match blocks.
Check syntax and effective values for the actual account/address, for example sudo sshd -T -C user=USER,host=HOST,addr=CLIENT_IP. Review passwordauthentication, kbdinteractiveauthentication, pubkeyauthentication, permitrootlogin and authenticationmethods.
sudo sshd -t
sshd -t returning success without output validates syntax, not every user's effective behavior.
# Ubuntu / Debian
sudo systemctl reload ssh
# RHEL / Rocky / AlmaLinux
sudo systemctl reload sshd
Choose ssh or sshd for the installed system. Prefer a validated reload; do not assume every service's restart either preserves or terminates all sessions. Keep console access.
ssh root@你的服务器IP
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no root@你的服务器IP
# 应该直接报 Permission denied (publickey)
Use genuinely fresh connections with ControlPath=none. Prove key-only access, then test password-only rejection and, if key-only is intended, keyboard-interactive rejection separately. Close the original session only after these tests and the intended administrative account succeed.
Commands such as ssh -i ~/.ssh/xxx -p 2222 [email protected] become hard to remember. Put host-specific settings in the local ~/.ssh/config:
Host vps1
HostName 203.0.113.10
User root
Port 22
IdentityFile ~/.ssh/id_ed25519
Host blog
HostName 203.0.113.20
User deploy
Port 2222
IdentityFile ~/.ssh/id_ed25519_blog
The addresses are documentation examples. Replace them, select the intended account and key, then connect with ssh vps1. Add IdentitiesOnly yes when an agent has many unrelated keys. Put specific Host sections before broad defaults because the client also usually uses the first obtained value.
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
AddKeysToAgent yes
ServerAliveInterval 60 sends encrypted keepalives; with ServerAliveCountMax 3, three unanswered probes lead to disconnection. It can help with idle NAT timeouts but cannot repair a failed network. See SSH connections that keep dropping. AddKeysToAgent requires an available agent and does not itself start one.
Protect ~/.ssh/config:
chmod 600 ~/.ssh/config
For one computer accessing several servers, -f selects a separate destination:
ssh-keygen -t ed25519 -C "blog-server" -f ~/.ssh/id_ed25519_blog
Set IdentityFile in config to that file. Separate keys reduce the scope of theft and make rotation easier. Compromise of a server does not automatically disclose a private key held only on your client; agent forwarding, copied keys and a compromised client are separate risks. Avoid forwarding your agent into untrusted servers.
For several computers accessing one VPS, generate a key on each trusted device and add one public-key line per device to authorized_keys.
# 服务器上查看当前有哪些公钥
cat ~/.ssh/authorized_keys
# 删掉某一台设备的那行之后,这台设备立刻失去访问权
Removing a line blocks future authentication with that key; it does not terminate an already authenticated session. Meaningful -C comments help identify owners. The original label 工作本-2026 is an example; use labels you recognize rather than generic user@localhost entries. A comment is not proof of ownership: record fingerprints too.
ssh-agent can hold signing keys so you do not repeatedly enter a passphrase:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
On systems with a session-managed agent, use it rather than starting unnecessary agents. Enter the passphrase when adding the key. Availability after logout/reboot depends on your operating system; consider ssh-add -t for a limited lifetime and ssh-add -D to remove loaded keys. Anyone who controls the client or agent socket may be able to request signatures.
On Apple's OpenSSH, this local ~/.ssh/config configuration can use the macOS keychain:
Host *
AddKeysToAgent yes
UseKeychain yes
UseKeychain is Apple-specific. Other OpenSSH builds may reject it; scope it to the appropriate client or use a supported IgnoreUnknown arrangement.
On Windows, configure the agent service from an elevated PowerShell, then add the personal key as its owner:
# 以管理员身份运行,设置 ssh-agent 开机自启
Set-Service -Name ssh-agent -StartupType Automatic
Start-Service ssh-agent
# 然后添加密钥
ssh-add $env:USERPROFILE\.ssh\id_ed25519
Built-in OpenSSH: supported Windows 10/11 installations can provide ssh through the OpenSSH Client optional feature. Check availability instead of assuming every installation has it. PowerShell and CMD use the same SSH options, with their own shell quoting and paths.
PuTTY: it uses .ppk files. Convert an OpenSSH private key with puttygen, protecting the exported file with a passphrase:
puttygen → Conversions → Import key → 选择 id_ed25519 → Save private key
The sequence means Conversions → Import key → select id_ed25519 → Save private key. Current PuTTY versions support Ed25519; check an older installation's capabilities.
Graphical clients: Termius, MobaXterm and FinalShell provide convenient sessions, file transfer or forwarding. Inspect where each client stores keys and whether optional cloud synchronization uploads private material. Do not assume every product or plan uses the same storage model.
Permissions 0644 for 'xxx' are too open or UNPROTECTED PRIVATE KEY FILE concerns the local private file. On Unix/appropriate WSL storage, use chmod 600 ~/.ssh/id_ed25519. On native Windows, repair owner and NTFS ACLs. WSL files on a mounted Windows drive may need metadata/ACL handling rather than a chmod command that has no practical effect.
For Permission denied (publickey), inspect the connection:
ssh -v user@host # 看详细过程
- No
Offering public key: check the local key path,-i, agent and matching Host section. - An
Offeringline followed by rejection: check the target account, complete public key inauthorized_keys, ownership, permissions and server policy. - Inspect the server log with
sudo tail -f /var/log/auth.logwhere that file exists; otherwise use the distribution's ssh/sshd journal. Match the timestamp and source address rather than unrelated scanner failures.
See SSH Permission denied troubleshooting for the complete diagnosis.
- If the old session is still open, restore the controlling settings, validate syntax and reload the correct service.
sudo sshd -t && sudo systemctl reload sshillustrates Ubuntu/Debian; adapt the service name. - If all SSH connections are gone, use a tested provider console to repair the settings and permissions.
- Otherwise use VPS rescue mode. Check UFW lockout recovery and Fail2Ban self-unban when authentication is not the real cause.
Host key verification failed can indicate a stale known_hosts entry after a rebuild, but verify the new fingerprint through a trusted channel first. Only then remove the obsolete record:
ssh-keygen -R 你的服务器IP
Use the actual hostname/address; a nondefault port may have an entry named [HOST]:PORT. An unexplained change is a security signal, not a reason to turn verification off.
ssh uses -p 新端口; replace the original placeholder with the actual port. scp uses uppercase -P. Allow the port in host/provider firewalls and update applicable Fail2Ban settings before closing the old access path. A different port mainly reduces scanning noise.
Lost key: from another authorized device, add the replacement device's public key to authorized_keys. With no remaining SSH access, use the provider console/rescue environment to add a key or briefly restore a carefully restricted password path. An independently authorized backup device or encrypted offline key backup makes recovery easier.
Exposed key: from a trusted administrative path, remove the matching public key from authorized_keys on every account and server where it is authorized:
# 先备份
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys.bak
# 编辑,删掉泄露的那行
vim ~/.ssh/authorized_keys
Preserve evidence, review active sessions and terminate unauthorized ones; removing the public line alone does not close them. Inspect other keys and changes:
cat ~/.ssh/authorized_keys
# 或者看最近的修改时间
stat ~/.ssh/authorized_keys
An unrecognized key may be legitimate provider provisioning, or an unauthorized addition. Establish its origin; treat unexplained changes as a suspected compromise and follow the first 24 hours after a VPS breach. Timestamps alone are not reliable proof of a clean host.
Key-only SSH addresses password guessing, while server maintenance and exposure still matter:
- A different SSH port reduces routine log noise, with little protection against a determined scan.
- Allow only necessary traffic; see VPS security hardening. Keep provider firewall rules consistent.
- Fail2Ban can still help other exposed authentication services and provide rate controls.
- Plan automatic security updates and reboots around service availability.
- Prefer a named administrative account with tested sudo. Decide separately whether root-key recovery access is required.
Do not expose databases, Redis or the Docker socket just to make administration convenient. Use a restricted SSH tunnel when appropriate; review database public exposure risks. A tunnel does not make Docker control harmless: its API can grant host-level power.
Will the provider console still work after SSH passwords are disabled? A genuine VNC/serial console follows a separate path from sshd, but console login may still require an OS credential. Some web terminals are SSH-based. Verify your provider's actual recovery method before changing authentication.
Should root be disabled completely? PermitRootLogin prohibit-password allows root keys, while no disables direct root SSH. A tested sudo account is a useful default; explicitly authorize any emergency root path rather than declaring one choice universal.
Can keys expire? OpenSSH certificates support validity intervals. Modern authorized_keys also supports expiry-time restrictions where the installed version provides them. Bare keys have no intrinsic expiry; confirm server support. An identity platform such as Keycloak does not automatically become an SSH CA: it needs a separately designed integration.
Can one key serve several machines? Yes, but theft affects all places that authorize it and revocation must reach each one. Separate keys help operationally; a server compromise alone does not reveal a client-only key.
Which Windows SSH executable is running? Use where ssh in CMD, where.exe ssh in PowerShell, or Get-Command ssh. Choose the intended Windows/Git/WSL client and its configuration path; PowerShell's where alias is not the CMD executable.
Should a retired device's public key be removed? Yes: remove its entry from authorized_keys everywhere it was authorized after testing replacement access.
Is a password manager a suitable key backup? Encrypted storage in products such as 1Password or Bitwarden can be better than an unprotected file. Review account access, recovery and export security. A hardware-backed key plus an independently protected recovery path may suit a different threat model; no single storage method removes client-compromise risk.
- VPS security hardening — firewall, rate controls and maintenance.
- SSH Permission denied — diagnose a rejected key.
- SSH connections that keep dropping — idle timeouts and unstable links.
- A VPS that cannot be reached — network and access diagnosis.
- Point a domain to your VPS — use a memorable hostname with client aliases.