code:
#!/usr/bin/python
import telnetlib
import sys
import time
import logging
class TelnetClient():
def __int__(self,):
self.tn = telnetlib.Telnet()
def login_host(self, host_ip, user_name, pass_word):
try:
# self.tn.open(host_ip, port=23)
self.tn = telnetlib.Telnet(host_ip,port=23)
except:
logging.warning("failed to connect to host:%s" %host_ip)
return False
self.tn.read_until(b'login:', timeout=10)
self.tn.write(user_name.encode('ascii') + b'\n')
self.tn.read_until(b'password:', timeout=10)
self.tn.write(pass_word.encode('ascii') + b'\n')
time.sleep(2)
command_result = self.tn.read_very_eager().decode('ascii')
if "incorrect" not in command_result:
logging.warning("login to host:%s successfully" %host_ip)
return True
else:
logging.warning("login to host:%s failed" %host_ip)
return False
def inputCommand(self, command):
print("%s" %command)
self.tn.write(b"command\n")
# must wait for the end of the command
time.sleep(2)
command_result = self.tn.read_very_eager()
#logging.debug("%s" %command_result)
print command_result
def logout(self):
self.tn.write(b"logout\n")
if __name__ == '__main__':
host_ip = sys.argv[1]
pass_word = ' '
user_name = 'admin'
complete = '>#'
telnet_client = TelnetClient()
print("we are try to telnet to %s" %(host_ip))
# login to the host, success:return true, fail: return false
if telnet_client.login_host(host_ip, user_name, pass_word):
telnet_client.inputCommand('command')
telnet_client.logout()
解释略。。