I am trying to automate generic telnet connections. I am relying heavily on REGEX to handle different login prompts. Currently, I am using the regex [Ll]ogin
, but the prompt causing me problems is the standard Ubuntu prompt:
b-davis login:
Password:
Last login: Mon Aug 29 20:28:24 EDT 2016 from localhost on pts/5
Because the word login is mentioned twice. Now the regex [Ll]ogin.{0,3}$
I thought should solve this, but it stopped matching all together. I tried something simpler, [Ll]ogin.
which should produce the same results as [Ll]ogin
but it doesn't!
I am using bytestrings because python throws a TypeError
if I don't. I feel the problem lies somewhere not regex related, so here is the entire piece of code:
import telnetlib
import re
pw = "p@ssw0rd"
user = "bdavis"
regex = [
b"[Ll]ogin.", # b"[Ll]ogin" works here
b"[Pp]assword",
b'>',
b'#']
tn = telnetlib.Telnet("1.2.3.4")
while type(tn.get_socket()) is not int:
result = tn.expect(regex, 5) # Retrieve send information
s = result[2].decode()
if re.search("[Ll]ogin$",s) is not None:
print("Do login stuff")
print(result)
tn.write((user + "\n").encode()) # Send Username
elif re.search("[Pp]assword",s) is not None:
print("Do password stuff")
tn.write((pw + "\n").encode()) # Send Password
elif re.search('>',s) is not None:
print("Do Cisco User Stuff")
tn.write(b"exit\n") # exit telnet
tn.close()
elif re.search('#',s) is not None:
print("Do Cisco Admin Stuff")
else:
print("I Don't understand this, help me:")
print(s)
tn.close()