mysqldump: [Warning] Using a password on the command line interface can be insecure.

解决 MySQL 密码命令行不安全警告的方法

当使用 mysqldump 命令并直接在命令行提供密码时,会出现这个警告:"Using a password on the command line interface can be insecure"。这是因为直接在命令行输入密码可能会被其他用户通过 ps 命令或系统日志看到。

推荐解决方案

1. 使用配置文件存储密码(推荐)

创建一个 ~/.my.cnf 文件(Linux/Mac)或 my.ini 文件(Windows),并设置权限为仅当前用户可读写:

touch ~/.my.cnf
chmod 600 ~/.my.cnf

然后在文件中添加以下内容:

[client]
user = your_username
password = your_password
host = localhost

之后运行 mysqldump 时就不需要提供密码了:

mysqldump -u your_username database_name > backup.sql

2. 使用环境变量传递密码

export MYSQL_PWD="your_password"
mysqldump -u your_username database_name > backup.sql
unset MYSQL_PWD

3. 使用交互式密码输入

mysqldump -u your_username -p database_name > backup.sql

执行后会提示输入密码,这样密码不会出现在命令行历史中。

4. 使用密码文件(不太安全)

mysqldump --defaults-extra-file=~/.mylogin.cnf -u your_username database_name > backup.sql

安全注意事项

  • 配置文件权限必须设置为 600(仅所有者可读写)
  • 不要将密码文件存储在公共可访问的位置
  • 定期更改密码
  • 考虑使用 MySQL 8.0+ 的 caching_sha2_password 插件增强安全性

以上方法中,使用配置文件(方法1)是最常用且推荐的方式。

实操



# 找出 cnf 文件放在哪
[root@localhost mysql-8.0]# find / -name '*.cnf'
/etc/my.cnf
/etc/pki/tls/openssl.cnf
/etc/pki/tls/ct_log_list.cnf
find: ‘/proc/1917582’: No such file or directory
find: ‘/proc/1917587’: No such file or directory
find: ‘/proc/1917588’: No such file or directory
/usr/local/mysql-8.0/data/auto.cnf

# 看看里面现在有哪些内容
[root@localhost mysql-8.0]# cat /etc/my.cnf 
[mysqld]
bind-address=0.0.0.0
basedir=/usr/local/mysql-8.0
datadir=/usr/local/mysql-8.0/data
port=3306
socket=/tmp/mysql.sock
character_set_server=utf8mb4
lower_case_table_names=1
log-error=/usr/local/mysql-8.0/data/mysql.log
pid-file=/usr/local/mysql-8.0/data/mysql.pid
explicit_defaults_for_timestamp=true
symbolic-links=0
[mysql]
default-character-set = utf8mb4

# 编辑 my.cnf 文件
[root@localhost mysql-8.0]# vi /etc/my.cnf

[client]
host = localhost
user = root
password = 2wsx@WSX 


# 导出文件 ,不要带 -p 密码
mysqldump -u your_username database_name > /opt/backup.sql


自动备份脚本

Linux shell crontab expdp 定时任务 自动逻辑备份数据库脚本 定时删除旧文件


#!/bin/sh
# ##################################################################
#             Powered by VipSoft
# ##################################################################
#
export MYSQL_HOME=/usr/local/mysql-8.0/
export PATH=$PATH:$MYSQL_HOME/bin
source /etc/profile
# 新版MySQL 不支持把密码直接写在命令行里
mysqldump -uroot vipsoft_db > /app/0.DB.Backup/vipsoft_$(date +%Y%m%d_%H%M%S).sql
#
# 删除10天前PE_开头的dmp文件
#
find /app/0.DB.Backup -mtime +10 -name "vipsoft_*"  -exec rm -f {} \;

posted @ 2025-07-11 12:06  VipSoft  阅读(196)  评论(0)    收藏  举报