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")
Related
How to delete common words from two documents thats extracted from two websites? I already extracted the news from two sites now I want to delete the common words from the two documents. I used the following code to extract news from two different websites:
from __future__import unicode_literals
import feedparser
import re
d=feedparser.parse('http://feeds.bbci.co.uk./news/rss.xml')
i=0
for post in d.entries
titl = post.title
desc = post.description
titl2 = tit1.replace('\\'," ")
desc1 = desc.replace('/'," ")
print(str(i) + ' ' + titl2)
i=i+1
print "indian Express"
g=feedparser.parse('http://www.rssmicro.com/rss.web?q=Android')
i=0
for pos in g.entries:
tit = post.title
#desc=post.description
tit4 = tit.replace('\\'," ")
print(str(i) + ' ' + tit4)
i=i+1
I'm trying to figure out how to sort logs for example...
User: test
Level: user
Domain: localhost
Time: 12pm
Blah: INFO
Date: 07-12-2016
Ip: 127.0.0.1
I would like the output text to be this also there is tab spaces.
User:Level:Domain:Time:Blah:Date:IP
If i get your question right, you're talking not about sorting, but about parsing. You have log strings which you want to convert to another format. The regex to match your log string would be
(?P<User>[^:]+):(?P<Level>[^:]+):(?P<Domain>[^:]+):(?P<Time>[^:]+):(?P<Blah>[^:]+):(?P<Date>[^:]+):(?P<IP>[^:]+)
However, since you have so many groups, it could be done much more efficiently, here's an example in python
import re
logString = "User:Level:Domain:Time:Blah:Date:IP"
logGroups = ["User", "Level", "Domain", "Time", "Blah", "Date", "IP"]
reLogGroups = "(?P<"+">[^:]+):(?P<".join(logGroups)+">[^:]+)"
matchLogGroups = re.search(reLogGroups,logString)
if matchLogGroups:
counter = 1
for logGroup in logGroups:
print(str(counter)+". " + logGroup + ": " + matchLogGroups.group(logGroup) + "\n")
counter += 1
The output is
1. User: User
2. Level: Level
3. Domain: Domain
4. Time: Time
5. Blah: Blah
6. Date: Date
7. IP: IP
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'
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]: