Python3+telnetlib Implementing the Telnet Client

Source: Internet
Author: User

I. Key points of the procedure

The six key questions that Python implements for Telnet clients and their answers are:

What libraries are used to implement Telnet client----telnetlib

How to connect the host----Two methods, one is the incoming IP address connection host (TN = telnetlib) when instantiating. Telnet (host_ip,port=23)), and the second is to instantiate the arguments first and then use the Open method to connect to the host (the method I use here)

How to enter the user name password----We use the READ_UNTILB function to listen, after the flag, use the Write method to transfer the user name password to the server

How to execute the command----is still using the Write method to send commands to the server, regardless of the data sent to the server with write; but note the need to encode into a bytes type

How to get command execution results----using the Read_very_eager () method, the method obtains all the input and output before the last fetch, and the bytes type is decode decoded.

How to exit Telnet---Exit Telnet using the Write method to submit the exit command to the server

Second, the program source code
ImportLoggingImportTelnetlibImport Timeclasstelnetclient ():def __init__(self,): self.tn=Telnetlib. Telnet ()#This function implements the Telnet login host    defLogin_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)returnFalse#wait for login to enter user name, wait up to 10 secondsSelf.tn.read_until (b'Login:', timeout=10) Self.tn.write (Username.encode ('ASCII') + b'\ n')        #wait for the password to enter the user name, up to 10 secondsSelf.tn.read_until (b'Password:', timeout=10) Self.tn.write (Password.encode ('ASCII') + b'\ n')        #delay two seconds to receive the return result, give the server enough response timeTime.sleep (2)        #Get Login Results        #Read_very_eager () gets all the output from the previous fetch, after the last acquisition.Command_result = Self.tn.read_very_eager (). Decode ('ASCII')        if 'Login Incorrect'  not inchcommand_result:logging.warning ('%s Login succeeded'%host_ip)returnTrueElse: Logging.warning ('%s Login failed with incorrect user name or password'%host_ip)returnFalse#This function implements the command that is passed over and outputs its execution results    defExecute_some_command (self,command):#Execute CommandSelf.tn.write (Command.encode ('ASCII') +b'\ n') Time.sleep (2)        #Get command ResultsCommand_result = Self.tn.read_very_eager (). Decode ('ASCII') logging.warning ('command Execution Result: \n%s'%Command_result)#exit Telnet    defLogout_host (self): Self.tn.write (b"exit\n")if __name__=='__main__': Host_ip='192.168.220.129'username='Root'Password='abcd1234'Command='WhoAmI'telnet_client=telnetclient ()#if the login result returns True, execute the command and then exit    ifTelnet_client.login_host (Host_ip,username,password): Telnet_client.execute_some_command (command) telnet _client.logout_host ()
View Code

Reference:

Https://docs.python.org/3/library/telnetlib.html

Python3+telnetlib Implementing the Telnet Client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.