Python 3 - 使用subprocess.call模块的stdout参数写入文件的问题

问题描述 投票:0回答:1

我正试图在我的渗透测试实验室中针对几个主机自动运行snmpwalk。基本上我想要做的是给我的python脚本一个目标IP列表(以文本文件的形式),让它对它们运行snmpwalk,并将结果存储在我创建的单独文件中(每个目标IP一个) 。这是我的代码的一部分,它针对live_list对象文件中包含的目标IP运行该工具:

def run_snmpwalk(selection):
    # Rewind file
    live_list.seek(0)
    if selection == '1':
            i = 0
            for line in live_list:

                    tgt_host = line.strip("/\n")
                    file_obj_array[i].write('[+] SNMPWalk user enumeration for IP:  ' + tgt_host + ' \n')
                    print('[+] Attempting to enumerate users from IP: ' + tgt_host)
                    exit_code = subprocess.call(['snmpwalk', '-c', 'public', '-v1', tgt_host, '1.3.6.1.4.1.77.1.2.25'], stdout=file_obj_array[i])
                    i += 1
                    if exit_code == 0:
                            print('[+] Success')
                    else:
                            print('[+] Something went wrong while executing snmpwalk ')

虽然它可能很糟糕,上面的代码按照我的意图工作,除了我似乎无法解决的一个小细节。

下面的行使用subprocess.call模块,并将stdoutparameter设置为我之前创建的文件,以包含命令的输出:

subprocess.call(['snmpwalk', '-c', 'public', '-v1', tgt_host, '1.3.6.1.4.1.77.1.2.25'], stdout=file_obj_array[i])

下一行应该在文件中写入一个头,上一个命令的输出被转储到该文件中:

file_obj_array[i].write('[+] SNMPWalk user enumeration for IP:  ' + tgt_host + ' \n')

但是,尽管在subprocess.call行之前执行,但上面的行不是以标题结尾,而是在文件的底部结束。这是上面函数的示例输出文件:

iso.3.6.1.4.1.77.1.2.25.1.1.5.71.117.101.115.116 = STRING: "Guest"
iso.3.6.1.4.1.77.1.2.25.1.1.6.97.117.115.116.105.110 = STRING: "austin"
iso.3.6.1.4.1.77.1.2.25.1.1.9.73.85.83.82.95.83.82.86.50 = STRING: "IUSR_SRV2"
iso.3.6.1.4.1.77.1.2.25.1.1.9.73.87.65.77.95.83.82.86.50 = STRING: "IWAM_SRV2"
iso.3.6.1.4.1.77.1.2.25.1.1.13.65.100.109.105.110.105.115.116.114.97.116.111.114 = STRING: "Administrator"
iso.3.6.1.4.1.77.1.2.25.1.1.14.84.115.73.110.116.101.114.110.101.116.85.115.101.114 = STRING: "TsInternetUser"

[+] SNMPWalk user enumeration for IP:  10.11.1.128

我无法弄清楚为什么subprocess.call设法在file_obj_array[i].write之前写入文件行,即使它在for循环之后。

任何想法都会有帮助。

谢谢!

python python-3.x subprocess
1个回答
1
投票

你必须刷新缓冲区:

def run_snmpwalk(selection, live_list, file_obj_array):
    # Rewind file
    live_list.seek(0)
    if selection == '1':
        for line, file_obj in zip(live_list, file_obj_array):
            tgt_host = line.strip("/\n")
            file_obj.write('[+] SNMPWalk user enumeration for IP:  {}\n'.format(tgt_host))
            file_obj.flush()
            print('[+] Attempting to enumerate users from IP: {}'.format(tgt_host))
            exit_code = subprocess.call(['snmpwalk', '-c', 'public', '-v1', tgt_host, '1.3.6.1.4.1.77.1.2.25'], stdout=file_obj)
            if exit_code == 0:
                print('[+] Success')
            else:
                print('[+] Something went wrong while executing snmpwalk ')
© www.soinside.com 2019 - 2024. All rights reserved.