0
votes

I have a bash script that logs into MySQL and creates a database. It has a sequence that requests the MySQL credentials (username and password) and then executes

read username
read password
read databasename
mysql -u$username -p$password -e "CREATE DATABASE $databasename;"

whenever I run this script, I get the warning "Using a password on the command line interface can be insecure"

What is the right, secure way to create a script like this where you need to log into MySQL and then run a command?

2
On modern Linux kernels, passing content through the environment is safer than the command line. (All accounts on the system, even untrusted ones like nobody, can read command lines; only the same account and root can read environment variables).Charles Duffy
BTW, always quote: -u"$username" -p"$password"; otherwise, an account with a password having spaces in it (or characters in the current value of IFS) is liable to misbehave. For similar reasons, it's better to use IFS= read -r password, so leading and trailing spaces and backslashes aren't discarded.Charles Duffy
(The environment-variable approach involves setting MYSQL_PWD; the documentation warns that this is insecure, but that's not the case when targeting modern Linux -- anyone who can read your environment variables can also read your credential files).Charles Duffy

2 Answers

1
votes

If you type ps aux, you can see every program currently executing on the computer, including the command line arguments. So... saying that "Using a password on the command line interface can be insecure" is a massive understatement.

See the documentation for other options. Specifically, make a credentials file, ensure it is only readable by you, then fill it with your authentication details.

0
votes

You can store your login details using the mysql_config_editor:

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

Then run your command line query like:

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

See this tutorial. There's an alternative method writing the configuration file directly for older versions of mySQL.