How to get a password from a shell script without

2020-01-25 02:48发布

I have a script that automates a process that needs access to a password protected system. The system is accessed via a command-line program that accepts the user password as an argument.

I would like to prompt the user to type in their password, assign it to a shell variable, and then use that variable to construct the command line of the accessing program (which will of course produce stream output that I will process).

I am a reasonably competent shell programmer in Bourne/Bash, but I don't know how to accept the user input without having it echo to the terminal (or maybe having it echoed using '*' characters).

Can anyone help with this?

9条回答
家丑人穷心不美
2楼-- · 2020-01-25 03:30

A POSIX compliant answer. Notice the use of /bin/sh instead of /bin/bash. (It does work with bash, but it does not require bash.)

#!/bin/sh
stty -echo
printf "Password: "
read PASSWORD
stty echo
printf "\n"
查看更多
Summer. ? 凉城
3楼-- · 2020-01-25 03:30

I found to be the the askpass command useful

password=$(/lib/cryptsetup/askpass "Give a password")

Every input character is replaced by *. See: Give a password ****

查看更多
4楼-- · 2020-01-25 03:33

This link is help in defining, * How to read password from use without echo-ing it back to terminal * How to replace each character with * -character.

https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-password/

查看更多
虎瘦雄心在
5楼-- · 2020-01-25 03:34

Here is another way to do it:

#!/bin/bash
# Read Password
echo -n Password: 
read -s password
echo
# Run Command
echo $password

The read -s will turn off echo for you. Just replace the echo on the last line with the command you want to run.

查看更多
Evening l夕情丶
6楼-- · 2020-01-25 03:37

Turn echo off using stty, then back on again after.

查看更多
Rolldiameter
7楼-- · 2020-01-25 03:39

One liner:

read -s -p "Password: " password

Under Linux (and cygwin) this form works in bash and sh. It may not be standard Unix sh, though.

For more info and options, in bash, type "help read".

$ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
  ...
  -p prompt output the string PROMPT without a trailing newline before
            attempting to read
  ...
  -s                do not echo input coming from a terminal
查看更多
登录 后发表回答