if语句评估后输出到两个文件之一

时间:2017-01-06 19:21:50

标签: python output python-3.5

我正在使用python nmap模块进行证书发现和监控。

import nmap
import time
import datetime
from contextlib import redirect_stdout
from datetime import date
import itertools

这是管理nmap扫描的功能。

SSLmonitor = nmap.PortScanner()
def SSLmon(IPaddress):
    now = datetime.datetime.now()
    filename = now.strftime("/results/%Y-%m-%dSSLmonWeekly.txt", "r")
    filename2 = now.strftime("/results/%Y-%m-%dSSLmonWeeklyExpiring.txt", "r")
    results = SSLmonitor.scan(hosts=IPaddress, arguments='--script=ssl-cert -p 443')
    # If statement checks to see if last scanned address has ['scan'].
    #print(results.keys())
    if 'scan' in results:
        hosts = results['scan']
        #print(hosts)
    # If host had cert on 443 try, else do pass.
    try:
        for host in hosts: # Chunk through the tuple.
            try:
                # Get the information for each host in the tuple
                cert = hosts[host]['tcp'][443]['script']['ssl-cert']
                try:
    for host in hosts: # Chunk through the dictionary to get the key value pairs we want.
        try:
            # Get the information for each host in the hecka-dictionary.
            cert = hosts[host]['tcp'][443]['script']['ssl-cert']
            cert2 = cert.replace('Not valid after:  ', '~')
            indexed = cert2.index('~')
                if datetime.date(int(cert2[indexed+1:indexed+5]), int(cert2[indexed+6:indexed+8]), int(cert2[indexed+9:indexed+11])) - datetime.date.today()
                    with open(filename, 'a') as f:
                        with redirect_stdout(f):
                            print("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'))
                else:
                    with open(filename2, 'a') as e:
                        with redirect_stdout(e):
                            print("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'))
            except Exception:
                pass
    except Exception:
        pass

我遍历我知道有证书的IP地址列表 在端口443上,并通过扫描仪运行它们。

#--------------------------------------------------------------
# Iterate through list of hosts with discovered certs
#--------------------------------------------------------------
with open("/weeklyscanlist/DiscoveredCertsByIP.txt", "r") as text_file:
    for line in itertools.islice(text_file, 1, 4250):
        SSLmon(str(line))

当我处理这样的输出时

if datetime.date(int(expDate[0]), int(expDate[1]), int(expDate[2])) - datetime.date.today() < datetime.timedelta(days = 30):
    print("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'), "this cert is expiring soon)
else:
    print("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'), "this cert is good for a while)

它工作正常,所以我知道我处理将输出写入文件的方式,但我找不到办法处理这个问题。 我也试过了

    if datetime.date(int(expDate[0]), int(expDate[1]), int(expDate[2])) - datetime.date.today() < datetime.timedelta(days = 30):
        fn = open(filename2, 'a')
        fn.write("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'))
        fn.close()
    else:
        f = open(filename, 'a')
        f.write("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n'))
        f.close()

没有成功。

2 个答案:

答案 0 :(得分:0)

似乎你对f.write的args是不正确的......试试:

if datetime.date(int(expDate[0]), int(expDate[1]), int(expDate[2])) - datetime.date.today() < datetime.timedelta(days = 30):
    fn = open(filename2, 'a')
    fn.write("{} {} {}".format("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n')))
    fn.close()
else:
    f = open(filename, 'a')
    f.write("{} {} {}".format("\n", IPaddress, cert.replace(':', '=').replace('commonName=', '\ncommonName=').replace('/', '\n')))
    f.close()

f.write接受一个论点......你把它传给了三个。

答案 1 :(得分:0)

这是你应该做的,跟进deweyredman的sage建议使用字符串格式:

  1. 使用字符串格式生成文件的输出行
  2. 使用if-then选择文件名
  3. 仅使用一个文件写入块来保持DRY

    iframe