Explain in detail the two ways that python connects telnet and ssh

  • 2021-12-11 18:24:05
  • OfStack

Directory Telnet Connection Mode ssh Connection Mode

Telnet Connection Mode


#!/usr/bin/env python
# coding=utf-8
 
import time
import telnetlib
import logging
 
__author__ = 'Evan'
 
save_log_path = 'result.txt'
file_mode = 'a+'
format_info = '%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s'
 
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
 
#  Add a record   Recorder function 
fh = logging.FileHandler(save_log_path, mode=file_mode)
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter(format_info))
logger.addHandler(fh)
#  Add display   Recorder function 
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter(format_info))
logger.addHandler(ch)
 
 
def telnet_handle(host='', port=''):
    handle = telnetlib.Telnet(host, port, timeout=10)
    handle.set_debuglevel(2)  # Display connect info (send command & received info)
    logger.debug('Connect host: {} port: {} successful'.format(host, port))
 
    try:
        # Get login prompt ' login : '  Enter the password after. 
        handle.read_until('login:', timeout=5)
 
        # Send a command   Login, username: admin  Password: admin
        handle.write('admin\n')  # User name 
        # If there is a prompt for entering a password, you can open this 1 Bar and correct the correct password prompt 
        #handle.read_until(' Enter password prompt ', timeout=5)
        time.sleep(1)
        handle.write('admin\n')  # Password 
        time.sleep(1)
        handle.write('en\n')  # Execute instructions 
        time.sleep(1)
        handle.write('sys\n')  # Execute instructions 
        time.sleep(1)
        handle.write('display running-config\n')  # Execute instructions 
        time.sleep(1)
        handle.write('show stack\n')  # Execute instructions 
        time.sleep(1)
 
        # Read all information 
        result = handle.read_very_eager()  
        logger.info('Received info: {}'.format(result))
    finally:
        handle.close()
 
if __name__ == '__main__':
    telnet_handle(host='192.168.10.1', port='23')

ssh Connection Mode


#!/usr/bin/env python
# coding=utf-8
 
import paramiko,sys,time
 
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect SSH Server 
client.connect("192.168.10.1",22,"admin","admin")
# Ways to execute commands 1    Connect linux Send fixed instructions 
stdin,stdout,stderr = client.exec_command("whoami")
time.sleep(2)
print(stdout.read())
stdin,stdout,stderr = client.exec_command("cat /root/lzhi/c_call_python.txt")
print(stdout.read())
stdin,stdout,stderr = client.exec_command("ls")
print(stdout.read())
stdin,stdout,stderr = client.exec_command("ls -la")
print(stdout.read())
 
# Ways to execute commands 2   Gets the command line arguments and deletes the arguments 1. Keep the commands that need to be executed 
buf = sys.argv
del buf[0]
str1 = ' '.join(buf)
print(str1)
# Execute the command given by the command line argument 
stdin,stdout,stderr = client.exec_command(str1)
#time.sleep(1)
print(stdout.read())

Related articles: