一、前言
有朋友问我如何让Linux的root用户在设置密码时也符合密码复杂度的要求,众所周知,root用户就是一个“流氓”,掌握服务器的生杀大权。我在网上找了一些文章,发现并不能对root用户做出限制。于是我就心生奇想,自己写一个passwd脚本,来一个偷梁换柱,替换掉系统的passwd命令,这样不就可以实现对root的限制了吗[也只是表面上的]
。在做下面的步骤时,最好先创建一个普通用户,并设置sudo密码,以防万一!
useradd -s /bin/bash -m test
echo "test:123456" |chpasswd
echo "test ALL=(ALL:ALL) NOPASSWD:ALL" >> /etc/sudoers
visudo -c #检测语法是否正确
操作有风险,最好在测试环境操作
二、准备脚本
1. password.py,放到/usr/bin/下,用于判断密码的复杂度
# @FileName :password.py
# @Time :2020/3/21 16:29
# @Author :anqixiang
# @Function :Detect Password Is Complex
import sys
digit_srt = '0123456789' #数字0~9
lowercase_list = [chr(i) for i in range(97,123)] #小写字母a~z
capital_list = [chr(i) for i in range(65,91)] #大写字母A~Z
special_character = "~!@#$%^&*()_+-*/<>,.[]\/" #把自己认为的特殊加符号进来
def check_pwd(pwd):
if len(pwd) < 8: #Password length is 8 or more
exit(1)
a = b = c = d = 0 #用作判断密码是否符合四分之三原则
for i in pwd:
if i in digit_srt:
a = 1 #表明密码中有数字
elif i in lowercase_list:
b = 1
elif i in capital_list:
c = 1
elif i in special_character:
d = 1
else:
exit(1)
if a + b + c + d >= 3:
exit(0)
else:
exit(1)
check_pwd(sys.argv[1])
2. password.sh 修改密码
#!/bin/bash
#判断位置参数是否合法
[ $# -gt 1 ] && echo "passwd: Only one user name may be specified." && exit 1
password_path=/usr/bin/passwd_os #系统的passwd命令
Check_Pwd(){
echo "Changing password for user $1."
stty -echo #关闭回显
read -p "New password:" pwd1
stty echo
echo
/usr/bin/password.py ${pwd1} #检测密码的合法性
if [ $? -ne 0 ];then
echo "BAD PASSWORD: The password is shorter than 8 characters" && exit 1
else
stty -echo
read -p "Retype new password:" pwd2
stty echo
echo
if [ ${pwd1} != ${pwd2} ];then
echo "Sorry, passwords do not match."
else
echo "$1:${pwd2}" |chpasswd
echo "passwd: all authentication tokens updated successfully." && exit 0
fi
fi
}
if [ `whoami` != "root" ];then
${password_path} $1 #如果是普通用户依然使用系统的passwd命令
else
if [ $# -eq 0 ];then
Check_Pwd root
else
if ! id $1 &>/dev/null;then
echo "passwd: Unknown user name $1." && exit 1
else
Check_Pwd $1
fi
fi
fi
偷梁换柱
cp -p /usr/bin/passwd /usr/bin/passwd_os
cp /root/password.sh /usr/bin/passwd
执行效果
输入123456
输入1qaz@wsx