When automating mysqldump it is necessary to pass authentication information along with the command. While you can pass the credentials on the command line this is considered unsafe as the password would be visible to all users using the ps afx command (for example).

A workaround for this is using expect a program that is meant to automate user interaction for terminal programs. expect simulates a tty and passes input to the controlled program depending on its output.

Here comes an example how to automate mysqldump using expect:

#!/bin/bash

# mysql credentials and connection data
db_host="localhost"
db_name="testdb"
db_user="jon"
db_pass="secret"

# using a here-document to pass commands to expect. 
# (the commands could be stored in a file as well)
expect <<EOF
# disable command output
log_user 0
# start the mysqldump process
spawn mysqldump -h$db_host -u$db_user -p $db_name
# wait for the password prompt
expect "password:"
# send the password (mind the \r)
send "$db_pass\r"
# enable output again
log_user 1
# echo all outout until the end
expect eof
EOF

Leave a Reply