Password is being used as a command

馋奶兔 提交于 2021-01-03 06:54:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!