class TelnetClient():
def __init__(self, ):
self.tn = telnetlib.Telnet()
# This function implements telnet Log on to the host
def login_host(self, host_ip, username, password):
try:
# self.tn = telnetlib.Telnet(host_ip,port=23)
self.tn.open(host_ip, port=23)
except:
logging.warning('%s Network connection failed ' % host_ip)
return False
# wait for login Enter the user name when it appears , Waiting for the most 10 second
self.tn.read_until(b'login: ', timeout=0.1)
self.tn.write(username.encode('ascii') + b'\n')
# wait for Password Enter the user name when it appears , Waiting for the most 10 second
self.tn.read_until(b'Password: ', timeout=0.1)
self.tn.write(password.encode('ascii') + b'\n')
# Delay for two seconds before receiving the returned results , Give the server enough response time
time.sleep(0.05)
# Get login results
# read_very_eager() What you get is all the output after the last acquisition and before this acquisition
command_result = self.tn.read_very_eager().decode('ascii')
if 'Logged Fail' not in command_result:
logging.warning('%s Login successful ' % host_ip)
return True
else:
logging.warning('%s Login failed , Wrong user name or password ' % host_ip)
return False
# This function implements the execution of the passed command , And output its execution result
def execute_some_command(self, command):
for i in range(len(command)):
# Carry out orders
self.tn.write(command[i].encode('ascii') + b'\n')
time.sleep(3)
# Get command results
command_result = self.tn.read_very_eager().decode('ascii')
logging.warning(' Command execution result :\n%s' % command_result)
# This function implements the execution of the passed command , And output the execution result
def excute_one_command_print(self, command):
# Carry out orders
self.tn.write(command.encode("ascii") + b'\n')
time.sleep(0.8)
# Get command results
command_result = self.tn.read_very_eager().decode("ascii")
logging.warning(' Command execution result :\n%s' % command_result)
# This function implements the execution of the passed command , And return its execution result
def excute_one_command_return(self, command):
# Carry out orders
self.tn.write(command.encode("ascii") + b'\n')
time.sleep(0.5)
# Get command results
command_result = self.tn.read_very_eager().decode("ascii")
# logging.warning(' Command execution result :\n%s' % command_result)
return command_result
# sign out telnet
def logout_host(self):
self.tn.write(b"exit\n")