当我尝试在终端内运行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。


当前回答

从https://gist.github.com/nestoru/4f684f206c399894952d

# Let us consider the following typical mysql backup script:
mysqldump --routines --no-data -h $mysqlHost -P $mysqlPort -u $mysqlUser -p$mysqlPassword $database

# It succeeds but stderr will get:
# Warning: Using a password on the command line interface can be insecure.
# You can fix this with the below hack:
credentialsFile=/mysql-credentials.cnf
echo "[client]" > $credentialsFile
echo "user=$mysqlUser" >> $credentialsFile
echo "password=$mysqlPassword" >> $credentialsFile
echo "host=$mysqlHost" >> $credentialsFile
mysqldump --defaults-extra-file=$credentialsFile --routines --no-data $database

# This should not be IMO an error. It is just a 'considered best practice'
# Read more from http://thinkinginsoftware.blogspot.com/2015/10/solution-for-mysql-warning-using.html

其他回答

如果您的MySQL客户端/服务器版本是5.6。使用mysql_config_editor工具来避免警告消息:

mysql_config_editor set --login-path=local --host=localhost --user=username --password

然后你可以在你的shell脚本中使用:

mysql --login-path=local  -e "statement"

而不是:

mysql -u username -p pass -e "statement"

另一种方法是使用sshpass调用mysql,例如:

sshpass -p topsecret mysql -u root -p username -e 'statement'

您还可以在脚本中运行mysql_config_editor,在指定登录路径时传入密码

expect -c "
spawn mysql_config_editor set --login-path=$mySqlUser --host=localhost --user=$mySqlUser --password
expect -nocase \"Enter password:\" {send \"$mySqlPassword\r\"; interact}
"

这将启动一个expect会话,该会话可用于脚本中与提示符交互

请看这篇文章

最好的解决方案是使用别名:

alias [yourapp]-mysql="mysql -u root -psomepassword -P3306 -h 127.0.0.1"

例如,把这个放在你的脚本中:

alias drupal-mysql="mysql -u root -psomepassword -P3306 -h 127.0.0.1"

然后在脚本中加载数据库:

drupal-mysql database_name < database_dump.sql

运行语句:

drupal-mysql -e "EXEC SOMESTATEMENT;"

这对我很管用 只要在$(mysql_command)之后添加2> null,它将只抑制错误和警告消息。