簡體   English   中英

Python不會寫入文本文件

[英]Python Won't write to text file

我正在嘗試使用以下代碼將IP地址從一個文件寫入另一個文件,如果它們發生30次以上:

#!/usr/bin/python

#open the auth.log file
myFile = open('auth.log','r') 

myTxtFile = open('blacklist2.txt','w') #open the Security_Test.txt for writing later

myTxtFile.write('The IP Addresses with more than 30 Attacks are:\n') #prints out a line of text ready for the outcome

ip_attacks = {}
count_attacks = 0

#go through each line of the file and return it to the variable line
for line in myFile.readlines():

    #get the IP address
    #we are working backwards to avoid the difference of the length of the NT logs
    attack_ip = list_of_line[-4]
    attack_ip_list= attack_ip.split('port')
    attack_address = attack_ip_list[0]
    if 'Failed password for' in line:
        #print '\'',attack_address,'\''
        if ip_attacks.has_key(attack_address):
            count_attacks = ip_attacks[attack_address]
            count_attacks = count_attacks +1
            ip_attacks[attack_address] = count_attacks
            #zero out the temporary counter as a precaution
            count_attacks =0 
        else:
            ip_attacks[attack_address] = 1
        if count_attacks > 30:
            myTxtFile.write(ip_attacks)

但是它不會寫入文本文件,唯一寫入文本文件的是第一行“攻擊次數超過30的IP地址是:”我在這里做錯了什么,這使我無法將ip_address從文件寫入另一個文件?

日志文件中的示例行:

Feb  5 08:25:47 j4-be02 sshd[2130]: Failed password for root from 5.199.133.223 port 50259 ssh2
Feb  5 08:25:55 j4-be02 sshd[2133]: Failed password for root from 5.199.133.223 port 57329 ssh2

您的代碼是錯誤的,因為您將count_attacks重置為零。 我相信您希望if語句為:

if ip_attacks[attack_address] > 30:
        myTxtFile.write(ip_attacks)

代替:

if count_attacks > 30:
        myTxtFile.write(ip_attacks)

編輯:順便說一句。 我相信這3行:

count_attacks = ip_attacks[attack_address]
count_attacks = count_attacks +1
ip_attacks[attack_address] = count_attacks

可以替換為:

ip_attacks[attack_address] += 1

編輯:問題的完整解決方案:

#!/usr/bin/python

from collections import defaultdict
#open the auth.log file
myFile = open('auth.log','r') 

myTxtFile = open('blacklist2.txt','w') #open the Security_Test.txt for writing later

myTxtFile.write('The IP Addresses with more than 30 Attacks are:\n') #prints out a line of text ready for the outcome

ip_attacks = defaultdict(int)
count_attacks = 0

#go through each line of the file and return it to the variable line
for line in myFile.readlines():

#get the IP address
#we are working backwards to avoid the difference of the length of the NT logs
attack_ip = list_of_line[-4]
attack_ip_list= attack_ip.split('port')
attack_address = attack_ip_list[0]
if 'Failed password for' in line:
    #print '\'',attack_address,'\''
    ip_attacks[attack_address] += 1


for key, value in ip_attacks.iteritems():
    if value > 30:
        myTxtFile.write(key)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM