Read console keystrokes with echo off



Is there any native way in Rust to read console keystroke codes with echo turned off?
…like blind password input in linux. I don’t care whether it’s an ANSI key code sequence or some constant like “KEY_UP”…

I could use ugly C-imports, like this:

extern crate libc;
extern {
  pub fn getchar() -> libc::c_int;

fn main() {
    loop {
        let ch = unsafe{ getchar() };
        println!("ANSI code: {}", ch);

and mock termios.h to turn echo off but I believe there should be some better native approach to do that in a nice cross-platform way…

PS, the code above on Windows doesn’t react on special keys like F1…F12, Backspace, Arrows etc, that is also an issue with C-imports…


On Windows you can use SetConsoleMode to disable ENABLE_ECHO_INPUT and then you can use ReadConsoleInput to retrieve raw events directly.


The best tool I’ve found for this sort of situation is Cargo’s search. We have a bunch of results, most of which are not relevant but third from the top is the rpassword crate, which claims to do what you’re asking for. I cannot promise it works, but quickly skimming the code reveals a lot of testing logic and support for both termios and SetConsoleMode.

awesome-rust, a curated list of “best of breed” libraries for common tasks, is also a very useful resource. It doesn’t list anything for password reading; perhaps you could nominate rpassword (in a PR) after confirming that it works.


You can use termion.
It has termion::TermRead::read_passwd(…) to accomplish what you want.