help with Python telnet script

I want to set all the routers in our network(20 mikrotik routers).
So, I decide to use the telnet access with python programming language.

First, I have tested on a mikrotik router.
The below is my python script.

#!/usr/bin/python

import getpass
import sys
import telnetlib
import time

HOST='my-mikrotik-ip-address'
PORT='21'
user= raw_input("Enter your remote account: ")
password= getpass.getpass()
tn=telnetlib.Telnet(HOST,PORT)
tn.read_until("Login: ")
tn.write(user + "\n")
if password:
   try:
       tn.read_until("Password: ")
       tn.write(password + "\n")
       print tn.read_until('>')
       tn.write("/ip add \n") 
       tn.read_until(">") 
       tn.write("\n") 
       tn.write(" print \n")
       print tn.read_until('>')
       time.sleep(10)
       print tn.read_all()
       tn.write("\n")
       tn.read_until(">")

   except  EOFError, socket.error:
       print time.strftime("%H:%M:%S  "),
       print "Telnet failure "

The result is not the one (“/ip address print”)

The result is below

MMM MMM KKK TTTTTTTTTTT KKK
MMMM MMMM KKK TTTTTTTTTTT KKK
MMM MMMM MMM III KKK KKK RRRRRR OOOOOO TTT III KKK KKK
MMM MM MMM III KKKKK RRR RRR OOO OOO TTT III KKKKK
MMM MMM III KKK KKK RRRRRR OOO OOO TTT III KKK KKK
MMM MMM III KKK KKK RRR RRR OOOOOO TTT III KKK KKK

MikroTik RouterOS 5.6 (c) 1999-2011 ttp://www.mikrotik.com/

[admin@[C]InC Solution] >
^[[?1;2c^[[60;3R


It doesn’t display the result for ‘/ip address print’


Is Anyone to help me? please, leave your comment.

Thanks for your reading.

I have encountered the same problem with you, thanks to your code to remind, I can print out the results returned by Telnet, and then learn from your code, successfully executed the command, in your code just before the command is executed with a" tn.read_until ( b’>’ )"The following is my successful debugging code, and I hope to help you, originates from Baidu translation.Debug version: Python3.2.3, routeros:3.2.7
#Telnet RouterOs & Run Command v0.1
import telnetlib,time
#config_user_password_port_etc.
HOST=‘127.0.0.1’
PORT=‘23’
user= ‘test’
password= ‘test’
command_1=‘ping 127.0.0.1 c 3’
command_3=‘quit’

tn=telnetlib.Telnet(HOST,PORT)
tn = telnetlib.Telnet(HOST)
#input user
tn.read_until(b"Login: “)
tn.write(user.encode(‘UTF-8’) + b”\n")
#input password
tn.read_until(b"Password: “)
tn.write(password.encode(‘UTF-8’) + b”\n")

tn.read_until(b’>‘)
tn.write(command_1.encode(‘UTF-8’)+b"\r\n")
time.sleep(5)
tn.read_until(b’>')
tn.write(command_3.encode(‘UTF-8’)+b"\r\n")

print(tn.read_all())
tn.close()