21

Possible Duplicate:
How to hide commands typed in a Linux shell?
Reading passwords without showing on screen in Bash Scripts

I would like to take a password as input, but I want user to be able to enter it just like other utilities handle it i.e. the characters doesn't appear on the screen. I tried searching regarding this, but found no exact answer.

I need to take in a variable, and then I would match the input with a pre-defined standalone password hard-coded variable sourced from one of the config files at the beginning of the script.

Expected behaviour

$./startScript
username: mtk
password: ********

* shown as placeholders. I need this part to be invisible. Currently the password is displayed as the user types it.

How to do this?

mtk
  • 27,530
  • 35
  • 94
  • 130

3 Answers3

33

If you use sh (or bash), you use read with option -s (secure).

read -s pass

will read password from user, not showing it to the output and store it to variable pass.

v154c1
  • 1,186
6

UNIX has 'getpass' C function to display a prompt and read the password with disabled echo.

The function gets the prompt string and returns a pointer to NULL-terminated string containing password. Don't forget about maximum passwords length (take a look at limits.h on your system for PASS_MAX or so).

Also pay attention that 'getpass' puts the password into internal static buffer, which is erased each time you invoke it. So, decent process should zero the buffer as soon as possible.

Here is a small program, showing the behavior:

#include <stdio.h>
#include <unistd.h>

int
main( int argc, char** argv ) {
    char* password = getpass( "Password: " );
    printf( "Your password is: '%s'\n", password );

    return 0;
}
Ivanhoe
  • 61
5

I think this code should do what you want:

#!/bin/bash

unset username
unset password
echo -n "username:"
read username
prompt="password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
         break
    fi
    prompt='*'
    password+="$char"
done