Industry guru Dave Taylor offers tech support on technical and business topics, including iPhone, iPod, Microsoft Windows, Sony PSP, cellphones, online advertising, CSS, Web design, business, Unix, Linux, SEO, Mac OS X, and shell script programming.     


How can I read a password without echoing it in C?

I'm trying to figure out how to disable the echo flag in C. I want to do this because I am coding a C program that must ask for a users password, so I would like to disable Echo, let the user enter his password, then re-enable Echo.


Dave's Answer:

Before I show you the solution in C, I want to start by demonstrating how to do this in a shell script, because they both demonstrate how to solve the problem and they both show that the solution is to learn just a bit about the keyboard device driver.

Specifically, we Unix old-timers refer to it as the tty, quite literally teletypewriter or teletype device. Think late 60's clattering printer / keyboard hooked up via a thick wire to a computational device the size of a small washing machine and you'd be on the money.

This device name is still around, and in fact the keyboard driver is still called the "tty". Try it, type tty on the command line in Linux:

$ tty
/dev/ttys000

Amazing, isn't it? Thirty years later...

On the Linux command line, the utility that lets you change the settings of this "tty" command is stty, and here's exactly how you could use this to turn off echo temporarily in a shell script to ask for a password:

save_state=$(stty -g)

/bin/echo -n "Account: "
read acct
/bin/echo -n "Password: "
stty -echo
read password # this won't echo
stty "$save_state"

echo ""
echo account = $acct and password = $password

When run, it looks like this:

Account: test
Password:
account = test and password = demo

Now, finally, let's convert that to a C program.

Fortunately, there's a very useful function in C that's widely available called getpasswd() which does all the "stty" heavy lifting. It makes things easy:

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

main()
{
  char acct[80], password[80];

  printf("Account: ");
  fgets(acct, 80, stdin);

  acct[strlen(acct)-1] = 0; /* remove carriage return */

  strncpy(password, getpass("Password: "), 80);
  printf("You entered acct %s and pass %s\n", acct, password);
}


If you want to do something more sophisticated where you output an asterisk each time they enter a character, you can check out some of the example code on the Ubuntu forums discussion.


More Useful Unix and Linux Help Articles:
✔   Copy and Paste from the Mac OS X Command Line?
I am constantly running commands in Terminal.app on my MacBook and then copying and pasting the results into email messages or documents. Yes,...
✔   Shell script to convert lowercase to title case?
As part of a project I'm working on, I find myself deep in a Linux shell script, needing to have a subroutine that...
✔   Can I script renaming files based on an XML data map?
I have a folder full of files which are named with four digits and a file extension e.g. 0312.file and an XML-file describing...
✔   Test for valid numbers in a Bash shell script?
In a different discussion on this site [see Redirecting input in a shell script] a visitor commented that "I was too busy trying...
✔   Review: iSSH for the iPad/iPhone
If you're running an online business like I am, there are times when you need to connect and log in to the server...

Let's stay in touch!
Sign up for my weekly AskDaveTaylor Newsletter and you'll receive even more tech and gadget help right to your inbox, along with exclusive news and industry updates. It's good stuff. I promise!
    Enter your name: and your email addr:  





Categorized: Unix and Linux Help   (Article 7931, Written by )
Tagged: c programming, linux device drivers, shell script programming
Previous: How can I stop people stealing my blog images and photos?
Next: Can I have Mac Preview sort thumbnails by creation date?




Reader Comments To Date: 2

Fjor said, on March 25, 2009 10:54 AM:

If you use Bash, the read command has the -s option to not echo characters to the terminal, and the -p option to show a prompt:

read -s -p "Password: "

So the example could be written as:

read -p "Account: " acct
read -s -p "Password: " password # this won't echo
echo
echo account = $acct and password = $password

Thanks for the C sample code.

Ashish said, on July 23, 2009 4:43 AM:

Great help! Thanks very much :)

Starbucks coffee cup I do have a lot to say, and questions of my own for that matter, but first I'd like to say thank you, Dave, for all your helpful information by buying you a cup of coffee!

I do have a comment, now that you mention it!











I will never send you any unsolicited email. Ever.






Check This Out Too...

 
Look for Answers
Need Help? Ask Dave Taylor!
Powered By
Linux Journal: Free Issue!


Follow Me on Pinterest

Find Me on Google+
ADT on G+
© 2002 - 2013 by Dave Taylor. All Rights Reserved.

Note: This web site is for the purpose of disseminating information for educational purposes, free of charge, for the benefit of all visitors. We take great care to provide quality information. However, we do not guarantee, and accept no legal liability whatsoever arising from or connected to, the accuracy, reliability, currency or completeness of any material contained on this web site or on any linked site. Further, please note that by submitting a question or comment you're agreeing to my terms of service, which are: you relinquish any subsequent rights of ownership to your material by submitting it on this site. My lawyer says "Thanks".
"Ask Dave Taylor®" is a registered trademark of Intuitive Systems, LLC.