Python Forum
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ipaddress.IPv4Network
#1
Hello all,

I am trying to go through a file of editors and find the IP addresses of edits if given. Some are IP ranges, others are single IP. It seems to work well, but it does not complete the entire file. It gets to the fourth to last IP range and then stops, even though there are four more IP addresses left. Any suggestions? The last few IP's are not ranges.

Code:
with open("fr_block.txt", "r", encoding="utf8") as f:
    next(f)
    for line in f:
        newline = line.split()
        try:          
            net = ipaddress.IPv4Network(newline[2])
            for a in net:
                f2.write(str(a) + "\n")
        except:
            pass
Reply
#2
don't use catch all exception. moreover you don't provide any feedback effectively you mask the error.
run
with open("fr_block.txt", "r", encoding="utf8") as f:
    next(f)
    for line in f:
        newline = line.split()        
        net = ipaddress.IPv4Network(newline[2])
        for a in net:
            f2.write(str(a) + "\n")
I guess you will get IndexError, assuming f2 is defined elsewhere in the code.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
This won't work. I have text names too. The third column is the editors

3856772 20161210022325 92.103.143.0/24
3856790 20161210125113 Fabio 46
3856802 20161210152829 Fouteurdezbeul
3856807 20161210162526 Tonybreboin
3856810 20161210172714 Nicodu94
3856814 20161210191108 Jvousencule
3856817 20161210191119 Tamere la ....
3856819 20161210192611 Sirus67
3856827 20161210210347 La personne que vous ne connaissz pas
3856829 20161210223023 Jasmin.Fillon
3856831 20161210231853 Genest 3000
Reply
#4
that was not solution, but explanation what's going on.

Not tested but something like
with open("fr_block.txt", "r", encoding="utf8") as f:
    next(f)
    for line in f:
        line = line.split()
        try:          
            net = ipaddress.IPv4Network(line[2])
        except ipaddress.AddressValueError:
            print('{} is not valid ip'.format(line[2]))
            continue
        else:
            for ipaddress in net:
                f2.write(str(ipaddress) + "\n") # assuming f2 is defined elsewhere in the code
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
It raises an exception at the first IP address that's not a network (p.s. f2 is defined before. It's the file. It contains either a username, IP address or IP address with a range. I want only the IP addresses and IP addresses with ranges.

Error:

Traceback (most recent call last):
File "E:\Data\Languages\French\test\block.py", line 20, in <module>
net = ipaddress.IPv4Network(line[2])
AttributeError: 'IPv4Address' object has no attribute 'IPv4Network'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "E:\Data\Languages\French\test\block.py", line 21, in <module>
except ipaddress.AddressValueError:
AttributeError: 'IPv4Address' object has no attribute 'AddressValueError'
Reply
#6
sorry, it's really late here. I overwrite ipaddress module with the variable name
with open("fr_block.txt", "r", encoding="utf8") as f:
    next(f)
    for line in f:
        line = line.split()
        try:          
            net = ipaddress.IPv4Network(line[2])
        except ipaddress.AddressValueError:
            print('{} is not valid ip'.format(line[2]))
            continue
        else:
            for ip_address in net:
                f2.write(str(ip_address) + "\n") # assuming f2 is defined elsewhere in the code
Here is how I test it
import ipaddress
items = ['blaba', '92.103.143.0/24']
for item in items:
    try:          
        net = ipaddress.IPv4Network(item)
    except ipaddress.AddressValueError:
        print('{} is not valid ip'.format(item))
        continue
    else:
        for ip_address in net:
            print(ip_address) # assuming f2 is defined elsewhere in the code
output
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thank you. It's still giving me the same result. It is not recognizing the last IP's as invalid, but it's not writing them either. Any help is greatly appreciated.
Reply
#8
Unless you show your full code as well as the input file I don't have other ideas
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
The code is not much different from what I've showed. The rest is below. I would attach the file, but I need to become a user. I can't figure out how to do that. Do you know how?

Thank you SO MUCH! I greatly appreciate it.


#change IP  ranges to ip addresses
import ipaddress
import re

#f = open("fr_block.txt", "r")
f2 = open("fr_block_2.txt", "w")

#next skips header
#limits date
#passes index into ip ranges and prints each ip
#except passes if not ip
#else ends the timestamp limit


with open("fr_block.txt", "r", encoding="utf8") as f:
    next(f)
    for line in f:
        line = line.split()
        try:          
            net = ipaddress.IPv4Network(line[2])
        except ipaddress.AddressValueError:
            print('{} is not valid ip'.format(line[2]))
            continue
        else:
            for ip_address in net:
                f2.write(str(ip_address) + "\n") 

Since I can't attach, this is the last part of the file. It correctly handles the last network IP, but then stops, even though there are a few more IP addresses.

3856772 20161210022325 92.103.143.0/24
3856790 20161210125113 Fabio 46
3856802 20161210152829 Fouteurdezbeul
3856807 20161210162526 Tonybreboin
3856810 20161210172714 Nicodu94
3856814 20161210191108 Jvousencule
3856817 20161210191119 Tamere la ....
3856819 20161210192611 Sirus67
3856827 20161210210347 La personne que vous ne connaissz pas
3856829 20161210223023 Jasmin.Fillon
3856831 20161210231853 Genest 3000
3856835 20161211010046 Prooftime
3856837 20161211060453 Loldu975
3856851 20161211125752 Willy400
3856853 20161211132918 Zorlakuil
3856861 20161211152952 Geolgeol
3856870 20161211171106 Le Zbeub Suprême
3856873 20161211174037 JuliiiiiAZ3
3856876 20161211174650 Emozill
3856881 20161211181423 En avant 75
3856883 20161211181646 Nicostella~frwiki
3856885 20161211181952 Nicostella
3856888 20161211185622 Tic tac--pilou
3856891 20161211191801 The Gambia
3856901 20161211213048 Murakami41100
3856903 20161211223800 Skola779
3856907 20161212041834 Piero San Giorgio
3856924 20161212093019 Claudiasachamatteolivio
3856930 20161212110726 DeleteDelete
3856945 20161212124514 Lol75000
3856952 20161212130436 Evann17
3856956 20161212130653 Seftyy
3856963 20161212135403 Enculedu95
3856966 20161212140821 MicLeMac
3856968 20161212141858 Teubé59
3856973 20161212144514 80.11.191.45
3856976 20161212150734 Bonneannée1915
3856984 20161212152628 Louanjacquet
3856989 20161212160221 Tk78delamort
3856999 20161212165701 Dy Di
3857011 20161212171128 Nini non
3857013 20161212171305 CaptainKrimi
3857016 20161212174630 Patoredu35
3857019 20161212181457 Avis de deces ADD
3857022 20161212183301 Nadir alaoui
3857035 20161212201434 Pnl Naha
3857040 20161212204936 ByeByeGaming232
3857041 20161212205012 ByeByegaming
3857045 20161212230153 Chukkyegg
3857047 20161212232237 Carré D'Al
3857068 20161213092606 Amonbeaufils
3857069 20161213092638 Lewishamiltonnnil
3857075 20161213100039 Les victoirer
3857110 20161213132700 Arthurba78270
3857116 20161213135317 XTB
3857122 20161213142633 82.127.147.119
3857123 20161213143758 PleutrePleutre
3857136 20161213152823 Ax200027
3857143 20161213154236 Jean-Michel du 59600
3857144 20161213154321 Ticlem
3857149 20161213155242 Cghciy
3857155 20161213161921 Weakz2703
3857156 20161213162356 Jacob steve
3857163 20161213174734 Maximogar
3857165 20161213180016 Abilton
3857187 20161213192630 Braun Strowman
3857189 20161213201200 Fidel Gastro
3857191 20161213204905 Samylepro
3857196 20161213220813 Maevalaptitekehba
3857198 20161213221430 Binkstobinks23
3857201 20161213223445 Alain Testin
3857204 20161213232153 Sebrider~frwikiquote
3857211 20161214081523 Steven95400z
3857214 20161214084335 Bernare
3857224 20161214104104 SCP-055
3857231 20161214105928 Monsieur moi
3857232 20161214110013 Maurice Liégeois
3857233 20161214111127 Chang.lee
3857245 20161214132345 Maitresse-corinne
3857260 20161214174240 Louloute 19120
3857264 20161214180453 Lea.bl
3857278 20161214203625 Philou234
3857292 20161214233650 Çimgori
3857301 20161215084101 Kikoo du 75
3857308 20161215093429 Yofiyof
3857311 20161215093840 82.127.76.135
3857328 20161215103842 Hardflay44
3857337 20161215123658 Leaaaaadllg
3857341 20161215130905 Luclash k i n g
3857353 20161215140453 Rahmane couscous
3857356 20161215141609 Vasy accepte la pd
3857375 20161215154248 Pistache38
3857377 20161215155058 Lololilololol
3857388 20161215182925 Bmxtrotinette
3857391 20161215193508 D,d,s,clic,dlckwkFigure me
3857393 20161215201424 Le créateur divin
3857404 20161215235437 Chicquelo
3857411 20161216070739 Bonjour les gens je suis 3428
3857426 20161216091706 158.64.5.241
3857428 20161216092339 Scorinex
3857435 20161216102435 Asxdrgb
3857438 20161216102740 Huiperezz
3857442 20161216104713 Tkunptipd
3857444 20161216111903 Lolol56860
3857462 20161216135804 Bekkar habiba 41
3857503 20161216224338 MostCult
3857506 20161216234706 Khalilabpos
3857514 20161217153407 Sylvain.321
3857518 20161217173012 HAMOCK
3857520 20161217180403 Hamdibencheikh
3857526 20161217195833 Philippe Pichon
3857531 20161217202321 De'rf(ty-
3857535 20161217221202 JASTIQUE
3857537 20161217223542 TOTOLEBG
3857540 20161217225842 Putain de merde
3857544 20161218062633 Caleger1247
3857548 20161218094920 Rayan Dandachi
3857560 20161218160454 Thomas sauron
3857562 20161218160907 Mohamed El-Mouttaqui
3857567 20161218182308 J'ai soulevé des montagnes
3857569 20161218184908 Bekkar taima
3857571 20161218185204 Anthony0799
3857581 20161218213048 Pierre-Arthur Vachel
3857583 20161218213056 KIWI SAUVAGE
3857593 20161219101650 Theobegue
3857598 20161219105436 Uindou
3857600 20161219110139 158.64.55.65
3857603 20161219141135 Valentine Navarro
3857604 20161219145838 Kevin koon
3857614 20161219170014 Jean dupotager38
3857620 20161219181925 AJ Green
3857621 20161219182037 Cki123
3857628 20161219205316 Wikipedia hater 2016
3857637 20161220031559 Yannou29kid
3857645 20161220084247 PépéTeLaMet
3857648 20161220093345 Maximeleboss 357
3857650 20161220094019 Zbeubzbebzbeubzbeb
3857661 20161220104851 Bonjourchezvous
3857678 20161220150345 Lllmm
3857680 20161220150441 Samuel Lemire 45212
3857682 20161220152437 Normandboily
3857691 20161220191641 M4cHiin360
3857692 20161220200721 Safoukoi
3857694 20161220201051 Chose1199
3857700 20161221003606 Albertine12
3857710 20161221093646 OuebFlow
3857719 20161221130055 MacLuck
3857722 20161221135125 Vitutu
3857729 20161221151652 Holy-Terrorist
3857736 20161221165537 Tonto el q lo lea
3857749 20161221194404 Kelian40
3857753 20161221204321 Lamn2627792
3857769 20161221234408 Le reup a pasco
3857776 20161222053817 Youssef lacrim
3857806 20161222191837 Megpac
3857811 20161222203950 Barry Blenkhorn
3857813 20161222204121 Cynthia Brady Cindy
3857814 20161222204233 Barry William Blenkhorn
3857824 20161223014719 Drop Dumb
3857826 20161223020027 Zbeubzbeub42
3857832 20161223133923 Dimidu06
3857841 20161223154000 Maxouille La Gerbille
3857845 20161223170307 Djed67
3857853 20161223190428 BLaaa
3857857 20161223201051 Ledixhouite
3857861 20161223232042 Emily Goldstein
3857880 20161224163649 JAAFAR YAHYA
3857881 20161224185059 État civil
3857883 20161224185706 Sourcefiable
3857893 20161225081659 Réponsecorrecteur
3857895 20161225082637 Hugo987
3857902 20161225095203 Ramirezo
3857904 20161225103202 Ramirezo2
3857906 20161225104750 Ramirezo4
3857908 20161225104803 Ramirezo1
3857909 20161225104815 Ramirezo3
3857910 20161225110344 Ramiréseau
3857917 20161225133411 Herladiste
3857921 20161225153118 I33333333
3857923 20161225153405 Raphouné
3857927 20161225170817 Corr21
3857933 20161225175224 Rezorami
3857935 20161225175430 Rezorami 6
3857937 20161225180051 Ramirezo 6
3857938 20161225180100 Ramirezo 7
3857946 20161225204642 Imenoou-s
3857950 20161225212027 ElenaDamon
3857970 20161226113146 TheGoldenTemplae
3857973 20161226124358 Tourangeo
3857975 20161226141416 Heu.....nique ta mére la gentille
3857990 20161226195127 Amlikartu de makka
3857992 20161226195542 Chloelys
3857994 20161226201148 3RIOLAN
3857996 20161226203605 Pizzapata
3857999 20161226205256 DavidRKR
3858003 20161226211019 Ou pas
3858004 20161226211749 Sivomey
3858006 20161226213411 Joël Noyeux
3858010 20161226224813 Gassi1
3858025 20161227102453 Ikeaba
3858035 20161227144549 Proxy hacking serveur ;bannisement
3858038 20161227150146 Viatonie
3858044 20161227172328 Vaterlopop
3858048 20161227174119 AchatVentes
3858050 20161227174428 Theyord
3858051 20161227175845 Sexeaddict
3858054 20161227181456 Alexandre62300
3858056 20161227182205 Akeldonst
3858058 20161227183734 IBRATV
3858068 20161227201051 Leobacker
3858070 20161227202216 Joeliiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
3858074 20161227205542 Luznarb59
3858076 20161227210201 Pizzarot
3858079 20161227215735 Anandali
3858084 20161227221704 Vincepat29
3858086 20161227223803 Andrea Bonaldi
3858089 20161227235151 Pizzahir
3858105 20161228111525 Lucasbaraton
3858109 20161228112454 F Varvarin
3858110 20161228112525 HK Bukowski
3858111 20161228112536 Pasapas 21
3858121 20161228131840 Alclaseo
3858123 20161228131848 Leta2742
3858129 20161228154741 Mouhamed mouhamed
3858132 20161228164519 Chiendroopy
3858144 20161228201019 WWE Nation
3858146 20161228202914 LaitBananesWiki
3858150 20161228212602 Soek91
3858181 20161229191816 Jskso
3858183 20161229192012 Fuckylizz
3858187 20161229205247 Lachouettefolle
3858197 20161229230319 TheBatHoovy
3858199 20161229230951 GillesLambla
3858203 20161229234008 Bonadeas2
3858222 20161230093352 SharkRUnDE
3858224 20161230095340 Lensuar
3858229 20161230124848 Elprofessor
3858233 20161230134008 Dejenrin
3858245 20161230154613 Helwan25
3858260 20161230215203 Puteprostituer
3858264 20161231001344 Jaimelesexe
3858274 20161231112745 Napoléon 5623
3858308 20161231174916 Teinam
3858320 20161231213839 Zeub13
3858323 20161231220648 Monsieur wikipidia
3858325 20161231222719 Issoulachancla

File attached. Thanks!

Attached Files

.txt   fr_block.txt (Size: 170.88 KB / Downloads: 587)
Reply
#10
The script runs and process file till the end.
As you can see from the screenshot, it process 4786 rows (excluding the header)
   
The last ip is 158.64.55.65 on line 4668 and it's the last one in the output file. The output file is too big to upload it here (some 37 Mb), but you can see the last ip is that one
   

I don't see what else you expect from the script. Here it is with minimal changes
import ipaddress
 
with open("fr_block.txt", "r", encoding="utf8") as fin, open("fr_block_2.txt", "w") as fout:
    next(fin)
    for i, line in enumerate(fin, start=1):
        line = line.split()
        try:          
            net = ipaddress.IPv4Network(line[2])
        except ipaddress.AddressValueError:
            print('{} is not valid ip'.format(line[2]))
            continue
        else:
            for ip_address in net:
                fout.write(str(ip_address) + "\n")
print('\n\nTotal rows processed (excluding the header row): {}'.format(i))
If I have time will add second version, e.g. I would use csv.DictReader to read the inpyt file, etc.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  help with ipaddress package jcrubaugh45 5 1,475 Jul-13-2022, 02:19 PM
Last Post: jcrubaugh45

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020