当我尝试在终端内运行MySQL上的以下命令时:

mysql -u $user -p$password -e "statement"

执行按预期工作,但它总是发出一个警告:

警告:在命令行界面上使用密码可能不安全。

但是,我必须使用存储密码的环境变量($password)来执行上面的语句,因为我想从Terminal中在bash脚本中迭代地运行命令,而且我绝对不喜欢等待提示显示并强迫我在一个脚本中输入密码50或100次的想法。我的问题是:

压制警告可行吗?如我所述,该命令可以正常工作,但是当我循环并运行该命令50或100次时,窗口变得非常混乱。 我应该遵守警告信息,不写我的密码在我的脚本?如果是这样的话,那么每次提示时我都必须输入密码吗?

Running man mysql没有帮助,说的只是

——显示警告 在每条语句后显示警告(如果有的话)。此选项适用于交互和批处理模式。

也没有提到如何关闭功能,如果我没有错过什么。

我使用的是OS X 10.9.1 Mavericks,使用的是自制的MySQL 5.6。


当前回答

一个简单的变通脚本。命名为“mysql”,并把它放在你的路径“/usr/bin”之前。其他命令的明显变体,或者警告文本不同。

#!/bin/sh

(
(
(
(
(
    /usr/bin/mysql "$@"
) 1>&9 
) 2>&1
) | fgrep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
) 1>&2 
) 9>&1

其他回答

这很简单。这是我的工作。

export MYSQL_PWD=password; mysql --user=username -e "statement"

MYSQL_PWD是MySQL直接或间接使用的环境变量之一。

从文档中可以看出:

MYSQL_PWD -连接mysqld时的默认密码。使用它是不安全的。请参见第6.1.2.1节“密码安全最终用户指南”。

另一个解决方案(例如,来自脚本):

 sed -i'' -e "s/password=.*\$/password=$pass/g" ~/.my.cnf
 mysql -h $host -u $user $db_name -e "$sql_cmd"

这里的-i "选项是为了兼容Mac OS x。标准的UNIX操作系统可以直接使用-i

最简单的方法是

mysql -u root -pMYPASSWORD -e "show databases" 2>/dev/null

下面是我如何让每日mysqldump数据库备份的bash脚本更安全地工作。这是克里斯蒂安·波特的伟大答案的扩展。

First use mysql_config_editor (comes with mysql 5.6+) to set up the encrypted password file. Suppose your username is "db_user". Running from the shell prompt: mysql_config_editor set --login-path=local --host=localhost --user=db_user --password It prompts for the password. Once you enter it, the user/pass are saved encrypted in your home/system_username/.mylogin.cnf Of course, change "system_username" to your username on the server. Change your bash script from this: mysqldump -u db_user -pInsecurePassword my_database | gzip > db_backup.tar.gz to this: mysqldump --login-path=local my_database | gzip > db_backup.tar.gz

不再暴露密码。

定义helper:

remove-warning () {
    grep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
}

使用它:

mysql -u $user -p$password -e "statement" 2>&1 | remove-warning

Tachaan !您的代码很干净,易于阅读

(用bash测试)