为何SSH在stdin已耗尽时仍能读取用户密码?
Great question—this is such a common point of confusion because it feels counterintuitive at first! Let’s break this down clearly, like we’re chatting through a tricky terminal quirk over coffee.
First: SSH Doesn’t Read Passwords From stdin (Usually)
Your initial assumption that SSH uses stdin for passwords makes total sense for most basic command-line tools, but SSH is built differently for security and reliability. Here’s the key:
- When SSH needs a password, it ignores the standard input stream entirely. Instead, it directly connects to your terminal device (often
/dev/ttyon Unix-like systems). - This terminal is a separate, dedicated communication channel tied to your interactive shell session—not the stdin/stdout streams that get rerouted when you use pipes (
|) or file redirection (</>).
Why SSH Works Even When stdin Is Exhausted
If you run something like echo "random text" | ssh user@your-server.com, SSH’s stdin is already filled (and exhausted) by the output of echo. But SSH doesn’t care—it skips stdin entirely and talks straight to your terminal.
Think of it this way: stdin is like a pipe that might be hooked up to another program or an empty file, but your terminal is a private, direct line between you and SSH. Even if the pipe is empty or closed, that private line stays open.
How SSH Actually Retrieves Your Password
Under the hood, SSH uses system calls (like open("/dev/tty") on Linux/macOS) to grab direct access to your terminal. Once it has that access:
- It turns off echo (so you don’t see the password you type on the screen) for security.
- It reads every character you type directly from the terminal device.
- After you hit enter, it turns echo back on so your future commands appear normally.
This design ensures your password never touches stdin, which means it can’t be accidentally captured by pipe logs, command history, or other programs listening in on the standard input stream.
A Quick Test to Prove It
Try running this command:
cat /dev/null | ssh user@your-server.com
/dev/null is an empty stream, so SSH’s stdin is immediately exhausted. But SSH will still prompt you for your password—solid proof it’s not using stdin at all.
内容的提问来源于stack exchange,提问作者Rogach

