如何将终端的输出写入格式的文件?

时间:2019-03-19 20:37:30

标签: python python-2.7

我想将脚本结果保存到文件中。脚本示例:

import os

def scan_ip():
    ip2 = raw_input('Enter ip of target: ')
    target = 'nmap -sP {}'.format(ip2)
    os.system(target + > '123.txt')

2 个答案:

答案 0 :(得分:1)

with open('123.txt', 'w') as my_file:
    my_file.write(target)

答案 1 :(得分:1)

您不应以这种方式这样做。首先,您需要使用output captured调用外部命令,然后将捕获的输出写入文件:

import subprocess

ip2 = raw_input('Enter ip of target: ')
p = subprocess.Popen(["nmap", "-sP", ip2], stdout=subprocess.PIPE)
out, err = p.communicate()
with open('123.txt', 'w') as f:
    f.write(out)