Python counter to text file - python

So im trying to analyse a log file and extract information from it.
One of the things im trying to do is extract a list of IP addresses that have more than 30 failed attempts. In this a failed attempt is one that starts with the line failed password for.
I have an idea for this that i wanted to try as i wasn't sure whether it will work.
If i use python to create a counter that looks for the keyword failed that i total and print out
This is what i have so far
failed_line=0
with open('blacklisttips.txt') as f2:
lines= f1.readlines()
for i, line in enumerate (lines):
if line.startswith(failed_line):
f2.write(line)
f2.write(lines[i+1])

So let's say your file looks like this:
failed password for 192.168.1.1
failed password for 192.168.1.2
...
more similar lines
import collections
prefix = failed password for
with open('path/to/file') as infile:
counts = collections.Counter(line.rsplit(" ",1)[1] for line in infile)

Related

Python reading text files

Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.

How to check if a block of lines has a particular keyword using python?

I am checking a text file with blocks of commands as following -
File start -
!
interface Vlan100
description XYZ
ip vrf forwarding XYZ
ip address 10.208.56.62 255.255.255.192
!
interface Vlan101
description ABC
ip vrf forwarding ABC
ip address 10.208.55.126 255.255.255.192
no ip redirects
no ip unreachables
no ip proxy-arp
!
File End
and I want to create a txt file where if in source file I am getting a pattern vrf forwarding ABC output should be interface Vlan101
as of now what I have done following script but it showing only the line which contains the pattern.
import re
f = open("output_file.txt","w") #output file to be generated
shakes = open("input_file.txt","r") #input file to read
for lines in shakes:
if re.match("(.*)ABC(.*)",lines):
f.write(lines)
f.close()
Easiest: read the file, cut where ! is, then for each of those, if there's the desired text, get the first line:
with open("input_file.txt") as r, open("output_file.txt", "w") as w:
txt = r.read()
result = [block.strip().split("\n")[0]
for block in txt.split('!')
if 'vrf forwarding ABC' in block]
w.write("\n".join(result))
Just to be clear, I imagine that you want to replace any instances of "interface Vlan101" with "vrf forwarding ABC". In this case, I had test.txt as the input file and out.txt as the output file with all the replaced instances as was needed. I used a list comprehension--with a list string method-- to replace the substrings of "interface Vlan101" with "vrf forwarding ABC".
with open("test.txt") as f:
lines = f.readlines()
new_lines = [line.replace("interface Vlan101", "vrf forwarding ABC" for line in lines]
with open("out.txt", "w") as f1:
f1.writelines(new_lines)
Hope this helps.
If you are just interested in the interface, you can do following as well.
#Read File
with open('sample.txt', 'r') as f:
lines = f.readlines()
#Capture 'interfaces'
interfaces = [i for i in lines if i.strip().startswith('inter')]
#Write it to a file
with open('output.txt', 'w') as f:
f.writelines(interfaces)
With your code you are going through the document line by line.
If you want to parse blocks (between "!"-signs) you could split the blocks into lines first (though if it's a really large document, you may need to consider something else as this will read the entire document into memory)
import re
f = open("output_file.txt","w") #output file to be generated
source = open("input_file.txt","r") #input file to read
lines = "".join(source) #creates a string from the document
shakes = lines.replace("\n","").replace("! ","\n")
# remove all newlines and create new ones from "!"-block delimiter
# retrieve all text before "vrf forwarding ABC"
finds = re.findall("(.*)vrf forwarding ABC",shakes)
# return start of line
# if the part you want is the same length in all,
# then you could use find[:17] instead of
# find to get only the beginning. otherwise you need to modify your
# regex to only take the first 2 words of the line.
for find in finds:
f.write(find)
f.close()
Alternatively, if you want to use match per line, you can do the same as above, however instead of replacing "!" with new line, you can just split it, and then use the previous code and go line by line.
Hope this helps!

error in ip2location python library

I am using ip2location Python library to find out location of corresponding ip address.I am trying to open a file containing ip address list and find out corresponding location through that.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-. LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN");//This is sample database
File1=open('test_ip.txt','r');//This is file containing ipaddress
Line=File1.readline();
While line:
rec = IP2LocObj.get_all(Line);
Line=File1.readline();
print rec.country_short
This code is giving error.You can check out the sample code here http://www.ip2location.com/developers/python
Please use the following Python codes.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN"); # This is sample database
with open('test_ip.txt') as f: # file containing ip addresses
for line_terminated in f:
line = line_terminated.rstrip('\r\n'); # strip newline
if line: # non-blank lines
print line
rec = IP2LocObj.get_all(line);
print rec.country_short

Python - Read value of variable from file

In bash, I have a file that stores my passwords in variable format.
e.g.
cat file.passwd
password1=EncryptedPassword1
password2=EncryptedPassword2
Now if I want to use the value of password1, this is all that I need to do in bash.
grep password1 file.passwd | cut -d'=' -f2
I am looking for an alternative for this in python. Is there any library that gives functionality to simply extract the value or do we have to do it manually
like below?
with open(file, 'r') as input:
for line in input:
if 'password1' in line:
re.findall(r'=(\w+)', line)
Read the file and add the check statement:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
Code:
import re
with open(file,"r") as input:
lines = input.readlines()
for line in lines:
if line.startswith("password1"):
print re.findall(r'=(\w+)',line)
There's nothing wrong with what you've written. If you want to play code golf:
line = next(line for line in open(file, 'r') if 'password1' in line)
I found this module very useful ! Made life much easier.

looking for line and linenumber in text file

I'm making a extra function for my chat program which allows you to register by typing a specific command that makes the host script save your peername and a name you insert in the terminal, its saved like this 57883:Jack in a txt file (names.txt) on the host machine. if a number of people have registered it'll look like this
57883:jack
57884:bob
57885:connor
57886:james
57887:zzhshsb93838
57887:ryan
when someone sends a message i want to know if his/her name is registered and if so, get the name to send to the client, so instead of seeing the peername the client will see the name of the person sending the message.
in order to do that i need to know if the peername is in the file and if so; where in the file, in which line. i've got this so far:
peer = sock.getpeername()
with open('names.txt', 'r') as d:
lines = d.readlines()
for peer in lines:
and i don't know how to find out in which line it was found, and when i know that how to seperate 57883 and ack and select jack and save it. Cheers!
with open("names.txt", "r") as f:
for i, line in enumerate(f):
numb, name = line.rstrip().split(":")
print i, numb, name
You can ask Python to provide a tuple of line number and line content for each line of the file (see enumerate(f)). Then you remove the line terminator (see line.rstrip()) and split the line to parts separated by the provided character (see split(":")). You have all three components available then.

Categories

Resources