当我尝试在终端内运行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。
来自@david-g的答案非常棒,但至少BSD grep将[Warning]解释为单个字符的正则表达式表示(匹配单词Warning中的任何一个字符)。
对于我的脚本,我使用了相同的方法,包装在一个函数中(为了简单起见,只匹配字符串的部分):
mysql() {
(
(
(
(
(
/usr/local/bin/mysql "$@"
) 1>&9
) 2>&1
) | grep -v 'Using a password on the command line interface can be insecure.'
) 1>&2
) 9>&1
}
out=$(mysql ...... 2>&1)
rc=$?
上面的代码将使用一组选项调用mysql,将过滤的stderr重定向到stdout,并在$opt中捕获组合输出,在$rc中捕获退出码。
一种方便(但同样不安全)的方法是使用:
MYSQL_PWD=xxxxxxxx mysql -u root -e "statement"
请注意,官方文件不建议这样做。
请参见6.1.2.1密码安全终端用户指南(Mysql手册for Version 5.6):
Storing your password in the MYSQL_PWD environment variable
This method of specifying your MySQL password must be considered extremely insecure and should not be used. Some versions of ps include an option to display the environment of running processes. On some systems, if you set MYSQL_PWD, your password is exposed to any other user who runs ps. Even on systems without such a version of ps, it is unwise to assume that there are no other methods by which users can examine process environments.
我使用的是:
mysql --defaults-extra-file=/path/to/config.cnf
or
mysqldump --defaults-extra-file=/path/to/config.cnf
其中config.cnf包含:
[client]
user = "whatever"
password = "whatever"
host = "whatever"
这允许您拥有多个配置文件-针对不同的服务器/角色/数据库。使用~/.my.cnf将只允许您拥有一组配置(尽管它可能是一组有用的默认值)。
如果你是基于Debian的发行版,并且以root用户运行,你可以跳过上面的步骤,使用/etc/mysql/debian.cnf进入…:
mysql——defaults-extra-file = / etc / mysql / debian.cnf