I need to build a script to get the telnet output of as many hosts as possible and save them to a separate file for each host. The script should run as a daemon.
For the moment i have a function that encapsulates the logic for do it for a single host with telnetlib
, but i do not how to proceed. I planned to open a process (multiprocessing.Process
) for each host but i suspect it's going to be a resource waste and it must to exist a better way :)
def TelnetLogSaver(hostname,ip,filename):
# open files and telnet sessions
f = open(filename,"a")
tn = telnetlib.Telnet(ip,23,TIMEOUT)
# login
e = tn.read_until("Login: ")
tn.write(USER+"\n")
# and password
e = tn.read_until("Password: ")
tn.write(PASSWORD+"\n")
# Connected. Start infinite loop to save messages log
while True:
e = tn.read_until(PROMPT,TIMEOUT)
if e is not "":
f.write(datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
f.write(e)
f.flush()
# avoid session timeout
tn.write("\n")
e = tn.read_until(PROMPT
I believe the following should do what your require, I took your original code and made it into a type of thread:
Hope this helps, if you have any problem update your question or leave a comment.