David Rojo David Rojo - 18 days ago 6
MySQL Question

Execute mysqldump with python and set the password via stdin

I want to execute a mysqldump in python and provide the password when it is requested from the mysqldump.

Adding the password in the command line is not an option, it must be provided via stdin.

This is what I've done so far:
command = [
'mysqldump',
'-h', mysqlhost,
'-P', mysqlport,
'-u', mysqluser,
'-p',
mysqldb
]

mysqlfile = mysqlpath + "/" + mysqldb + ".sql"
with open(mysqlfile, "w+") as file:
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=file)
p.communicate(input=mysqlpass)
p.wait()


But when I execute the code the terminal hangs requesting the password.

Thank you.

Answer

You can use pexpect for that. This is modified code as I had to test it, but you get the idea:

import pexpect

command2 = 'mysqldump -h localhost -u root -p xyzzy'

mysqlfile = "/tmp/foo.sql"
with open(mysqlfile, "w+") as file:
    p = pexpect.spawn(command2)
    p.expect("Enter password: ")
    p.sendline("foobar")
    q = p.read()
    p.wait()
    file.write(q)

here "foobar" is my database password.

Hannu

Comments