I am writing a script to print all IPs in CIDR notaion, but I do not want to print first and last IPs as they are not usable.
from netaddr import IPNetwork
ipc = raw_input('Enter The IP Range ')
n = 0
for ip in IPNetwork(ipc):
n = n + 1
print '%s' % ip
print 'Total No of IPs are ' + str(n)
This means that if I give 12.110.34.224/27 I should get 30 IPs as result, removing first and last IPs as /27 means 32 IPs.
That should do it.
for ip in list(IPNetwork(ipc))[1:-1]:
Related
I have 2 files, file1.txt - which has 100's of IP Address line by line and on my second file(file2.txt), I have an entry ip_address which need to replaced by the actual ip address from the file1. How to do it in Python.
Your help is much appreciated
Eg:
less File1.txt
10.10.10.1
10.10.20.1
10.20.10.10 etc
less File2.txt
[/tmp/test/ip_address]
whitelist = *
I am looking for my output to be like this:
[/tmp/test/10.10.10.1]
whitelist = *
[/tmp/test/10.10.20.1]
whitelist = *
[/tmp/test/10.20.10.10]
whitelist = *
etc.
Using a simple iteration.
Ex:
with open("File1.txt") as infile, open("File2.txt", "w") as outfile:
for line in infile: #iterate each line
outfile.write("[/tmp/test/{}]\n whitelist = *\n\n".format(line.strip())) #Write content to file
I am beginner to python and i made telnet access to two routers R1and R2 through( for x in range (1,3) :) loop and i want to include in the same loop, loop back interfaces for each router example:
R1 only have interface loopback 1 1.1.1.1 255.255.255.255
R2 only have interface loopback 2 2.2.2 255.255.255.255
I successfully created the loop back interfaces but am not able to assign the ip address for each one .
import getpass
import sys
import telnetlib
user = raw_input("Enter your Telnet Username: ")
password = getpass.getpass()
for n in range (1,3):
HOST = "10.1.1." + str(n)
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("config t\n")
tn.write("int l " + str(n) +"\n")
tn.write("ip add str(n) . str(n) . str(n) . str(n) 255.255.255.255 \n")
tn.write("router eigrp 1\n")
tn.write("net 0.0.0.0\n")
tn.write("end\n")
tn.write("sh ip int br\n")
tn.write("exit\n")
print tn.read_all()
Thanks
the result of:
tn.write("ip add str(n) . str(n) . str(n) . str(n) 255.255.255.255 \n")
Will be a string: ip add str(n) . str(n) . str(n) . str(n) 255.255.255.255
Change that line to:
tn.write("ip add " + str(n) + "." + str(n) + "." + str(n) + "." + str(n) + " 255.255.255.255 \n")
import re
data = []
tcp_dump = "17:18:38.877517 IP 192.168.0.15.43471 > 23.195.155.202.443: Flags [.], ack 1623866279, win 245, options [nop,nop,TS val 43001536 ecr 287517202], length 0"
regex = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(^length (\d+))'
data_ready = re.findall(regex, tcp_dump)
print(data_ready)
data.append(data_ready)
print(data)
this code currently needs to grab 2 IPv4 addresses and the length of a packet and cast them into a 2-d list. so far the first half of my regex does just that with the IPv4 addresses. my problem comes down to grabbing the length. i get the output:
[('192.168.0.15', '', ''), ('23.195.155.202', '', '')]
instead of the desired output of:
['192.168.0.15', '23.195.155.202', '0']
any ways to fix the regex?
EDIT
so it turns out, the regex seperated works (just the first half or just the second half), i cant seem to get them to work combined.
This should do it. You just need to make some of your parenthesis non-capturing and do some data cleaning
import re
data = []
tcp_dump = "17:18:38.877517 IP 192.168.0.15.43471 > 23.195.155.202.443: Flags [.], ack 1623866279, win 245, options [nop,nop,TS val 43001536 ecr 287517202], length 0"
regex = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:length (\d+))'
# make the returned tuples into two lists, one containing the IPs and the
# other containing the lengths. Finally, filter out empty strings.
data_ready,lengths = zip(*re.findall(regex, tcp_dump))
list_data = [ip for ip in list(data_ready) + list(lengths) if ip != '']
print(list_data)
data.append(list_data)
print(data)
output:
['192.168.0.15', '23.195.155.202', '0']
I wouldn't call it IP address matching (as 192.168.0.15.43471 is not valid IP address) but text parsing/processing. Optimized solution with re.search() function:
import re
tcp_dump = "17:18:38.877517 IP 192.168.0.15.43471 > 23.195.155.202.443: Flags [.], ack 1623866279, win 245, options [nop,nop,TS val 43001536 ecr 287517202], length 0"
result = re.search(r'((?:\d{1,3}\.){3}\d{1,3})(?:\.\d+) > ((?:\d{1,3}\.){3}\d{1,3})(?:\.\d+).*(\d+)$', tcp_dump)
result = list(result.groups())
print(result)
The output:
['192.168.0.15', '23.195.155.202', '0']
I need to parse a file that contains flat text and extract both valid ip addresses and obfuscated ip addresses.
(ie. 192.168.1[.]1 or 192.168.1(.)1 or 192.168.1[dot]1 or 192.168.1(dot)1 or 192 . 168 . 1 . 1)
Once the data is extracted I need to convert them all to valid format and remove duplicates.
My current code places the ip addresses into a string, which should be a dict? I know I need to use some kind of recursion to set the key value, but I feel there is a more efficient and modular way to complete the task.
import json, ordereddict, re
# define the pattern of valid and obfuscated ips
pattern = r"((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])[ (\[]?(\.|dot)[ )\]]?){3}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))"
# open data file that contains ip addresses and other text
with open ("sample.txt", "r") as myfile:
text=myfile.read().replace('\n', '')
# put non normalized ip addresses in a dictionary
ips = {"data": [{"key1": match[0] for match in re.findall(pattern, text) }]}
# normalized ip addresses
for name, datalist in ips.iteritems():
for datadict in datalist:
for key, value in datadict.items():
if value == "(dot)":
datadict[key] = "."
if value == "[dot]":
datadict[key] = "."
if value == " . ":
datadict[key] = "."
if value == " .":
datadict[key] = "."
if value == ". ":
datadict[key] = "."
# write valid ip address to json file
with open('test.json', 'w') as outfile:
json.dump(ips, outfile)
Sample data file
These are valid ip addresses 192.168.1.1, 8.8.8.8
These are obfuscated 192.168.2[.]1 or 192.168.3(.)1 or 192.168.1[dot]1
192.168.1[dot]1 or 192.168.1(dot)1 or 192 .168 .1 .1 or 192. 168. 1. 1. or 192 . 168 . 1 . 1
This is what an invalid ip address looks like, they should be excluded 256.1.1.1 or 500.1.500.1 or 192.168.4.0
Expected result
192.168.1.1, 192.168.2.1, 192.168.3.1 , 8.8.8.8
My intended goal:
Need to pull IP address out of a string as i loop through pinging different subnets.
Example of string i will be searching:
>>> pingout = subprocess.getoutput('ping -c' + ' ' + str(1) + ' ' + '10.20.' + str(234.) + str(4))
>>> print(pingout)
PING 10.20.234.04 (10.20.234.4) 56(84) bytes of data.
64 bytes from 10.20.234.4: icmp_seq=1 ttl=64 time=4.01 ms
--- 10.20.234.04 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 4.016/4.016/4.016/0.000 ms
>
I want to use something like this.
match = re.search(r'?<=...........)ping', pingout)
Or this but need to exclude the 'ping' in the result.
match = re.search(r'.............ping',pingout)
Given:
txt='''\
PING 10.20.234.04 (10.20.234.4) 56(84) bytes of data.
64 bytes from 10.20.234.4: icmp_seq=1 ttl=64 time=4.01 ms
--- 10.20.234.04 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 4.016/4.016/4.016/0.000 ms'''
For the first IP address (with 'PING' in the line), you can do:
print(re.search(r'^PING\s*(\d+\.\d+\.\d+\.\d+)', txt, re.M).group(1))
For the second IP address (with 'ping' in the line), you can do:
print(re.search(r'^\D+(\d+\.\d+\.\d+\.\d+)\s*ping', txt, re.M).group(1))
Either case, prints 10.20.234.04
You can use tons of different regexes to extract those IP, I think the closest one to your solutions is:
>>> s
'--- 10.20.234.04 ping statistics ---'
>>> re.findall(".{12}(?= ping)", s)
['10.20.234.04']
But;
>>> import socket
>>> socket.gethostbyname("google.com")
'173.194.39.199'
Would be much better I think(Don't know if it works on subnets tho, but I think they must be the same thing.).
>>> import re
>>> m = re.match(r"PING .+ \((.+)\) .+ bytes of data.", "PING 10.20.234.04 (10.20.234.4) 56(84) bytes of data.")
>>> m
>>> m.groups()
('10.20.234.4',)
If I were going to use the regex repeatedly I would do:
ip_re = re.compile(r"PING .+ \((.+)\) .+ bytes of data.")
m = ip_re.match(pingout)
Note this catches the IP exactly once when ping prints its first line. No need to keep searching. You could extend the regex to catch the amount of data sent or the responses if you need to do so.
Try this regex,
match = re.search(r'.*PING ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*', PINGOUT)
match.group(1)
Example:
>>> match = re.search(r'.*PING ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*', "PING 10.20.234.04")
>>> match.group()
'PING 10.20.234.04'
>>> match.group(1)
'10.20.234.04'