Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 904
David Rojo Avatar asked Apr 28 '26 13:04

David Rojo


1 Answers

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

like image 136
Hannu Avatar answered May 01 '26 03:05

Hannu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!