密码被用作命令

2024-10-03 21:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从python文件运行命令:

p = subprocess.Popen("mysqldump -h" + hostname + " -u" + mysql_user + " --password=" + mysql_pw + " " + db + " >   dump_" + hostname + "_" + timestamp + ".sql", shell=True)

但是--password=甚至-p一直挂在我的密码字符串上

密码与此结构类似:

Z@F&sfeafxegwa

命令行错误:

'sfeafxegwa' is not recognized as an internal or external command,
operable program or batch file.

Tags: or文件命令密码dbmysqlpassworddump
2条回答

您需要引用密码来保护shell元字符(例如&)不被shell特别对待,例如:

cmd = "mysqldump -h {} -u {} -p'{}' {} > dump_{}_{}.sql".format(
    hostname, mysql_user, mysql_pw, db, hostname, timestamp)
subprocess.run(cmd, shell=True, check=True)

但是,如果密码本身可以包含引号,这将不起作用。更好的选择是将参数列表传递给subprocess,然后自己进行重定向:

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)

正如评论中已经提到的,不要使用shell=True。见https://docs.python.org/3/library/subprocess.html#security-considerations。你知道吗

将参数列表直接传递给Popen构造函数,而不是让shell进行拆分。你知道吗

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
    )

shell=True的问题可以在旧版本的文档中得到更好的解释:https://docs.python.org/2/library/subprocess.html#frequently-used-arguments

相关问题 更多 >