Shell-输入密码转换为*

Code:

read -p "请输入使用者都名称:" USER
echo -e "请输入使用者密码: \c"
while : ;do
	char=` #这里是反引号,tab键上面那个
	stty cbreak -echo
	dd if=/dev/tty bs=1 count=1 2>/dev/null
	stty -cbreak echo
	` #这里是反引号,tab键上面那个
	if [ "$char" = "" ];then
		echo #这里的echo只是为换行
		break
	fi
	PASS="$PASS$char"
	echo -n "*"
done

补充:Shell输入密码时关闭屏幕回显

stty -echo

read -p “请输入使用者密码: ” PASS

stty echo

这样在输入密码的时候就不会显示了


方法二:

如果你需要写一段与用户交互,且需要输入一些敏感信息的(例如:用户密码、License等),那么直接用printf+read的方式,就会把用户输入的信息显示在屏幕了,这是不符合信息安全的,而且对客户体验来说也显得不够专业,所以就需要将用户输入的密码转换为*,样式如下:

please input your passwd:1234
修改为:
please input your passwd:****

那么具体如何实现呢,请往下看……

#!/bin/sh       
getchar() {    
  stty cbreak -echo    
  dd if=/dev/tty bs=1 count=1 2> /dev/null    
  stty -cbreak echo    
}       
printf “Please input your passwd: ”        
while : ; do    
	ret=`getchar`    
	if [ x$ret = x ]; then    
		echo    
		break    
	fi    
	str=”$str$ret”    
	printf “*”    
done
echo “Your password is: $str”
posted @ 2017-08-29 16:32  bamboo233  阅读(355)  评论(0编辑  收藏  举报