【问题标题】:Executing bash commands in python error [duplicate]在python错误中执行bash命令[重复]
【发布时间】:2016-02-20 11:05:57
【问题描述】:

我正在尝试编写一个 python 脚本来在连接到本地主机时使用暴力破解(和密码)测试 4 位密码。需要运行的命令是:

echo password pincode | nc localhost 30002 >> /tmp/joesPin/pinNumber

(将响应写入新文件)。

这在编写为 bash 脚本时有效,但我正在努力使用 Python 中的子进程模块。

import subprocess

password = "UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ"

for i in range(10000):

    pincode = str('{0:04}'.format(i)) #changes 4 to 0004
    subprocess.call('echo', password, pincode,'|','nc localhost 30002 >> /tmp/joesPin/' + pincode,shell=True)

我希望它调用:

echo UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 0001 | nc localhost 30002 >> /tmp/joesPin/0001

【问题讨论】:

    标签: python bash cygwin subprocess


    【解决方案1】:

    在 Python 中,有多种方法可以通过管道输出命令的输出。

    选项 1:您可以设置 subprocess.call 命令的 stdout 参数并将输出写入某处。

    选项 2:您可以在 Popencall 中使用 subprocess.PIPE 并保存输出以与其他命令一起使用。

    proc = subprocess.Popen(['echo', password, pincode], stdout=subprocess.PIPE)
    output = proc.communicate()[0] # now contains the output of running "proc"
    
    file = '/tmp/joesPin/pinNumber'
    with open(file, 'a+') as out:
        subprocess.call(['nc localhost 30002'], stdout=out, shell=True)
    

    subprocess.call 中设置stdout 字段会将子进程的输出写入stdout 中给定的文件描述符。

    将第一个进程的输出用作第二个进程的标准输入:

    proc = subprocess.Popen(['echo', password, pincode], stdout=subprocess.PIPE)
    output = proc.communicate()[0] # now contains the output of running "proc"
    
    file = '/tmp/joesPin/pinNumber'
    proc2 = subprocess.Popen(['nc localhost 30002'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    proc2.stdin.write(output)
    result = proc2.communicate()[0]
    
    # now you can write the output to the file:
    with open (file, 'a+') as outfile:
        outfile.write(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 2019-03-13
      • 2011-08-18
      相关资源
      最近更新 更多