So this is my code:
class telnet(object):
"""conexiune"""
def __init__(self):
HOST = "route-views.routeviews.org"
user = "rviews"
password = ""
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ", 5)
tn.write(user + "\r\n")
tn.read_until("Password: ", 5)
tn.write(password + "\r\n")
print tn.read_until(">", 10)
tn.write("show ip route 192.0.2.1"+"\r\n")
self.y = tn.read_until("free", 10)
print self.y
tn.write("exit"+ "\r\n")
tn.close()
def re(self):
self.m = re.search(r' Known via "bgp \d{0,5}"', self.y)
if self.m:
print self.m.group(0)
else:
print False
What I need to do is return self.m instead of printing it. If I write 'return "This answer is: "+self.m', I get this error:
return "The answer is: " + self.m.group(0) TypeError: cannot concatenate 'str' and '_sre.SRE_Match' objects
If I use print it prints it, but I don't know how to do it with a return statement.
This is what it has to return:
Known via "bgp 6447"
from this telnet output: route-views> show ip route 192.0.2.1
Routing entry for 192.0.2.1/32
Known via "bgp 6447", distance 20, metric 0
Tag 19214, type external
Last update from 208.74.64.40 4w1d ago
Routing Descriptor Blocks:
208.74.64.40, from 208.74.64.40, 4w1d ago
Route metric is 0, traffic share count is 1
AS Hops 1
Route tag 19214
MPLS label: none
route-views>
I know that return is used for functions - that's why I added the '+'. Btw I'm a Python beginner. Any help would be appreciated.
I think in your 'return' statement you just missed out the '.group(0)'.
Try :
if self.m:
return self.m.group(0)
From documentation
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup.
'Isaac'
>>> m.group(2) # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple.
('Isaac', 'Newton')
So, try this
>>> import re
>>> y = ' Known via "bgp 54574"'
>>> m = re.search(r' Known via "bgp (\d{0,5})"', y)
>>> print m.group(1) if m else False
54574
>>> y = ' Known via "bg p 54574"'
>>> m = re.search(r' Known via "bgp (\d{0,5})"', y)
>>> print m.group(1) if m else False
False
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.