密码被用作命令
Password is being used as a command
我正在尝试 运行 来自 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.
您需要引用密码以保护 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)
但是,如果密码本身可以包含引号,这将不起作用。更好的选择是将参数的 list 传递给 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
我正在尝试 运行 来自 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.
您需要引用密码以保护 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)
但是,如果密码本身可以包含引号,这将不起作用。更好的选择是将参数的 list 传递给 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