重置mysql密碼
環境說明:
環境 | 版本號 |
---|---|
操作系統 | RHEL8 |
mysql | 8.0.17 |
1 mysql
手動修改密碼步驟
- 修改my.cnf 文件在【mysqld】字段下面加入 skip-grant-tables,並關閉mysql服務
- 啓動mysql服務
- mysql進入數據庫
- use mysql
- select user,host,authentication_string from user 查看密碼,一般是密文看不了
- 輸入flush privileges否則修改密碼會出現錯誤
- ALTER USER ‘root’@‘localhost’ IDENTIFIED BY ‘新密碼’;
- flush privileges
- 重啓數據庫
2 使用 Shell
腳本重置
shell實現內容:
- 輸入要設置的密碼(判斷密碼是否合規及兩次輸入匹配)
- 密碼修改
#!/bin/bash
password() {
while true;do
while true;do
echo "Your password must be a string containing case and special characters and no less than 8 bits."
printf -- '\n';
echo -e "enter password: "
printf -- '\n';
stty -echo
read passwd1
stty echo
echo -e "please input password,again: "
printf -- '\n';
stty -echo
read passwd2
stty echo
[[ $passwd1 = $passwd2 ]] && passwd=`echo $passwd1` && break || (echo "passwords not match,retry." && printf -- '\n');
done
strlen=`echo $passwd | grep -E --color '^(.{8,}).*$'` #密碼長度是否8位以上(包含8位)
strlow=`echo $passwd | grep -E --color '^(.*[a-z]+).*$'` #密碼是否有小寫字母
strupp=`echo $passwd | grep -E --color '^(.*[A-Z]).*$'` #密碼是否有大寫字母
strts=`echo $passwd | grep -E --color '^(.*\W).*$'` #密碼是否有特殊字符
strnum=`echo $passwd | grep -E --color '^(.*[0-9]).*$'` #密碼是否有數字
if [ -n "${strlen}" ] && [ -n "${strlow}" ] && [ -n "${strupp}" ] && [ -n "${strts}" ] && [ -n "${strnum}" ]
then
(echo "Your password can be used;") && printf -- '\n' && break
else
echo "Your password can not be used; input another password."
printf -- '\n';
fi
done
}
wait(){
for ((i=0;i<9;i++))
do
tput sc; tput civis
echo -ne $(date +'%Y-%m-%d %H:%M:%S')
sleep 1
tput rc
done
tput el; tput cnorm
printf -- '\n';
}
chage(){
fn=$(date '+%Y-%m-%d'-%H:%M:%S).sql && echo $fn && touch /tmp/$fn
echo "use mysql;" >> /tmp/$fn
echo "flush privileges;" >> /tmp/$fn
echo "ALTER USER 'root'@'%' IDENTIFIED BY '$passwd';" >> /tmp/$fn
echo "flush privileges;" >> /tmp/$fn
grep "skip-grant-tables" /etc/my.cnf && a=1 || a=0
grep "skip-grant-tables" /etc/my.cnf | grep -v ^\# && b=1 || b=2
if [[ $a -eq $b ]];
then
echo "already add skip-grant-tables to my.cnf"
printf -- '\n';
elif [[ $a -eq 1 ]] && [[ $b -eq 2 ]];
then
sed -i 's/\#skip-grant-tables/skip-grant-tables/g' /etc/my.cnf
else
sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/my.cnf
fi
ps -ef| grep /usr/sbin/mysqld | grep -v pts/0
if [[ $? -eq 0 ]];
then
systemctl restart mysqld
else
systemctl start mysqld
fi
wait
[[ $? -eq 0 ]] && mysql < /tmp/$fn | tail -f
[[ $? -eq 0 ]] && rm -rf /tmp/$fn && sed -i 's/skip-grant-tables/\#skip-grant-tables/g' /etc/my.cnf && systemctl restart mysqld
[[ $? -eq 0 ]] && echo "Well, i guess your password is ****************"
printf -- '\n';
}
password && chage
3 更簡單的辦法
把密碼寫在紙上: