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


当前回答

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

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

其他回答

下面是我如何让每日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

不再暴露密码。

如果你想在命令行中使用密码,我发现这可以过滤掉特定的错误消息:

mysqlcommand 2>&1 | grep -v "Warning: Using a password"

它基本上是将标准错误重定向到标准输出——并使用grep删除与“Warning: using a password”匹配的所有行。

通过这种方式,您可以看到任何其他输出,包括错误。我将此用于各种shell脚本等。

如果你碰巧使用Rundeck来调度你的任务,或者任何其他你要求mylogin.cnf文件的平台,我已经成功地使用下面的shell代码在进行sql调用之前为文件提供了一个新的位置:

if test -f "$CUSTOM_MY_LOGINS_FILE_PATH"; then
   chmod 600 $CUSTOM_MY_LOGINS_FILE_PATH
   export MYSQL_TEST_LOGIN_FILE="$CUSTOM_MY_LOGINS_FILE_PATH"
fi

...

result=$(mysql --login-path=production -NBA -D $schema -e "$query")

其中MYSQL_TEST_LOGIN_FILE是一个环境变量,可以设置为与默认文件不同的文件路径。

如果您运行在一个fork进程中,并且不能移动或复制文件到$HOME目录,这尤其有用。

请在这里查看文档。

我使用的是:

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

就我个人而言,我使用脚本包装器来捕获该错误。下面是代码示例:

#!/bin/bash

#echo $@ | cat >> /home/mysqldump.log 2>/dev/null
ERR_FILE=/tmp/tmp_mdump.err

# Execute dumper
/usr/bin/mysqldump $@ 2>$ERR_FILE

# Determine error and remove tmp file
ERROR=`cat $ERR_FILE`
rm $ERR_FILE

# Handle an error
if [ "" != "$ERROR" ]; then

        # Error occured
        if [ "Warning: Using a password on the command line interface can be insecure." != "$ERROR" ]; then
                echo $ERROR >&2
                exit 1
        fi
fi