Python telnet login function implementation code

Read the table of contents

For source code, please refer to: starnightcyber/scripts

The TelnetClient class is mainly used to encapsulate the basic operations of logging in and executing commands.

The source code is as follows, or please check: scripts/telnet/telnet.py

The telnet protocol is a member of the TCP/IP protocol suite, and is the standard protocol and main method of the Internet remote login service. It provides users with the ability to complete remote host work on the local computer. Use the telnet program on the end user's computer to connect to the server.

Terminal users can enter commands in the telnet program, and these commands will run on the server, just like directly typing on the server's console, and the server can be controlled locally. To start a telnet session, you must enter a user name and password to log in to the server. Telnet is a commonly used method to remotely control a Web server.

code show as below

#! /usr/bin/env python
# - *- coding:utf-8-*-import logging
import telnetlib
import time
# Telnet login authentication related
auth ={"user_prompt": b'Username:',      #Enter username prompt
" password_prompt": b'Password:',    #Enter password prompt
" enter": b'\r',            #Carriage return
" remote_enter": b'\n\r',}classTelnetClient(object):
def __init__(self):
self.tn = telnetlib.Telnet()    # Telnet client
def login(self, ip, port, tel_dict):"""
telnet login
: param ip:Target ip
: param port:Destination port
: param tel_dict:Password dictionary
: return:login successful(True)or login failed(False)"""
msg ='trying to login {}:{} telnet service'.format(ip, port)print(msg)
# telnet login
for username, password in tel_dict.items():
# Create a telnet connection
try:
self.tn.open(ip, port)
except:
logging.warning('%sNetwork connection failed'% ip)return False,''
msg ='try user:[{}], password:[{}]'.format(username, password)print(msg)
# Login attempt
try:
# Waiting for the username to prompt user_After the prompt appears, enter the user name
self.tn.read_until(auth['user_prompt'], timeout=3)
self.tn.write(username.encode('ascii')+ auth['enter'])
# Waiting for the password prompt password_After the prompt appears, enter the password
self.tn.read_until(auth['password_prompt'], timeout=3)
self.tn.write(password.encode('ascii')+ auth['enter'])
# Delay two seconds before receiving the returned result, giving the server enough response time
time.sleep(2)
# Get login results,read_very_eager()What you get is all the output after the last acquisition before this acquisition
command_result = self.tn.read_very_eager().decode('ascii')
# print('=== ', command_result)
prompt, _ = command_result.split('- ')
# print('=== ', prompt.strip())
# If there is no prompt to enter the user name in the returned result, it means that the login is successful
if auth['user_prompt'] not in command_result.encode('ascii'):print('login successful')return True
else:continue
except:
pass
return False
def execute_command(self, command):"""
Execute some commands
: param command:Command to execute
: return: None
"""
try:
self.tn.write(command.encode('ascii')+ auth['enter'])
time.sleep(2)
# Get command result
command_result = self.tn.read_very_eager().decode('ascii')print('== ', command_result)
except:print('something went wrong...')
pass
# Exit telnet, keep
def logout_host(self):
self.tn.write(b"bye\r")if __name__ =='__main__':
# parameter
ip ='172.16.176.120'
port ='2570'
tel_dict ={'admin':'admin','aaa':'bbb','':''}
# Sign in
tn =TelnetClient()
tn.login(ip, port, tel_dict)
# Excuting an order
command ='ver'
tn.execute_command(command)
# drop out
tn.logout_host()

The execution output is as follows:

# python3 telnet_brute.py
trying to login 172.16.176.120:2570 telnet service
try user:[admin], password:[admin]try user:[aaa], password:[bbb]try user:[], password:[]
login successful
== ver
Version :PAS_SIPPROXY_6.0.0.3.0.190831, Compile Time:16:18:41, Feb 252020
Return value:1
SipPrxoy-

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python telnet login function implementation code
Python ATM function implementation code example
Python drawing rose implementation code
Python enumerate() function
Python function buffer
Python|Flask realizes login function
Python custom function basics
Join function in Python
Python built-in function -compile()
Python function basic learning
Python data analysis-apply function
Python3 built-in function table.md
Python SMS bombing code
Python Print print timer function
Python high-order function usage summary!
Python code to find bugs (2)
Python code to find bugs(7)
How to comment python code
Python realizes online translation function
Python code to find bugs(4)
Python code to find bugs (3)
Python code to find bugs(9)
Python implementation of gomoku program
Python regular expression example code
Python tornado upload file function
Python implements code block folding
Python magic function eval () learning
Python install OpenCV sample code
Python code to find bugs(6)
How Python implements FTP function
Python code to find bugs (1)
Python code to find bugs(8)
Python implements verification code recognition
Python code to find bugs(5)
Is python code case sensitive
Python GUI simulation implementation calculator
Python implements image stitching function
Python high-order function usage summary!