密码正用作命令

时间:2017-10-04 15:39:32

标签: python cmd python-3.4

我试图从python文件中运行命令:

  <ul class="cargroup" *ngFor="let group of groups; let i = index;">
  // group being the make of car in this instance

    <li *ngFor="let car of this.carList">

      <app-car-info [car]="car" *ngIf="car?.makeId == group.id"></app-task>
     // component that shows all the info about the car

    </li>

  </ul>

p = subprocess.Popen("mysqldump -h" + hostname + " -u" + mysql_user + " --password=" + mysql_pw + " " + db + " > dump_" + hostname + "_" + timestamp + ".sql", shell=True) 甚至--password=仍然被我的密码字符串挂起

密码与此结构类似:

-p

命令行错误:

Z@F&sfeafxegwa

2 个答案:

答案 0 :(得分:2)

正如评论中已提到的,请勿使用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

答案 1 :(得分:1)

您需要引用密码来保护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)