问题
I'm trying to run a command from a python file:
p = subprocess.Popen("mysqldump -h" + hostname + " -u" + mysql_user + " --password=" + mysql_pw + " " + db + " > dump_" + hostname + "_" + timestamp + ".sql", shell=True)
But the --password=
and even -p
keep getting hanged up on my password string
The password is similar to this structure:
Z@F&sfeafxegwa
the command line error:
'sfeafxegwa' is not recognized as an internal or external command,
operable program or batch file.
回答1:
As already mentioned in the comments, don't use shell=True
. See https://docs.python.org/3/library/subprocess.html#security-considerations.
Pass the list of arguments directly to the Popen
constructor, instead of letting the shell do the splitting.
with open('dump_{}_{}.sql'.format(hostname, timestamp), 'w') as dump_file:
p = subprocess.Popen(
[
'mysqldump', '-h', hostname, '-u', mysql_user,
'--password={}'.format(mysql_pw), db
],
stdout=dump_file
)
The issue with shell=True
is better explained in the older version of the documentation: https://docs.python.org/2/library/subprocess.html#frequently-used-arguments
回答2:
You need to quote the password to protect shell metacharacters (such as &
) from being treated specially by the shell, e.g.:
cmd = "mysqldump -h {} -u {} -p'{}' {} > dump_{}_{}.sql".format(
hostname, mysql_user, mysql_pw, db, hostname, timestamp)
subprocess.run(cmd, shell=True, check=True)
However, this won't work if the password itself can contain quotes. A better alternative would be to pass the list of arguments to subprocess
and do the redirection yourself:
args = ["mysqldump", "-h", hostname, "-u", mysql_user, "-p{}".format(mysql_pw), db]
outfile = "dump_{}_{}.sql".format(hostname, timestamp)
with open(outfile, "w") as f:
subprocess.run(args, check=True, stdout=f)
来源:https://stackoverflow.com/questions/46568887/password-is-being-used-as-a-command