2017-01-06 46 views
-1

我正在使用python nmap模塊執行證書發現和監視。if語句評估後輸出到兩個文件之一

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() 

沒有成功。

+1

你可以發佈你的stacktrace嗎? – deweyredman

+0

f.write只有一個參數...嘗試格式化它 – deweyredman

回答

0

這裏是你應該做的事情,在deweyredman的明智建議以下爲使用字符串格式化:

  1. 使用字符串格式化以生成文件
  2. 使用的輸出線的IF-THEN挑文件名
  3. 只能使用一個文件寫入塊保持乾爽

    dt_diff = datetime.date(int(expDate[0]), int(expDate[1]), int(expDate[2])) - datetime.date.today() 
    which_filename = filename if dt_diff < datetime.timedelta(days = 30) else filename2 
    with open(which_filename, 'a') as f: 
        line = '\n%s %s' % (
         IPaddress, 
         cert.replace(':', '=' 
         ).replace('commonName=', '\ncommonName=' 
         ).replace('/', '\n'),) 
        f.write(line) 
    
+0

我上面發佈的代碼有一個很大的問題,因爲當我傳遞了一個非常不同的nmap參數時,它是一個腳本的過時版本。所以如果有人使用它,並且爲了說明爲什麼元組中的關鍵值對如此不同,那就是爲什麼。我道歉。也有人說這是解決方案,謝謝你的幫助。 – Ryan

0

看來你的參數傳遞給f.write是不正確的......試試:

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需要一個參數...你傳遞這三人。