How to SSH to Network Devices with Python

Keywords: Python ssh network shell

[ TOC ]

0. Preface

Since the last article "How to telnet to network devices with python", we have simply demonstrated using the telnetlib library, but telnet is not recommended in real life.
The SSH(Secure Shell) protocol is also part of the TCP/IP protocol family, with port number 22, which can be used as a method of remote management instead of telnet.
SSH provides two-way authentication, data encryption and other methods to ensure data security, SSHv2 version is recommended

1. Test environment and key code explanation

1.1 Simple Test Environment

  1. Using the python3 environment
  2. Use third-party Netmiko modules (based on Paramiko libraries)
  3. Simple experimental environment

1.2 Key Codes

import xx: import module
Class xx: define a class
Def xx: Define function
try-except: Handles exceptions that may be thrown
ssh.enable(): Enter enable mode
ssh.find_prompt(): Returns the current prompt
ssh.send_command(): Send a query command and return the result
ssh.send_config_set(): Send configuration command to target device
ssh.disconnect(): Close the connection

Tips: Import ConnectHandler and import Netmiko have the same effect.

2. Full code

'''
//Welcome to the WeChat Public Number:'diandijishu'
  //This platform is for network engineers to share their daily technical and project case experiences.
  //In order to consolidate and enhance technical capabilities and even share what you have learned,
  //Also welcome all engineers to share and grow together.
'''

#!/usr/bin/env python
#coding:utf-8

from netmiko import ConnectHandler
from netmiko.ssh_exception import NetMikoTimeoutException
from netmiko.ssh_exception import NetMikoAuthenticationException
from datetime import datetime
import time
import logging
from my_devices import device_list as devices

'Define Classes'
class SSH_Client():
    'Definition login_host Function for landing devices'
    def login_host(self , a_device):
        try:
            self.ssh = ConnectHandler(**a_device)
            self.ssh.enable()
            reply = self.ssh.find_prompt()
            print('>' * 10 + 'The successful login results are as follows:' + '>' * 10 + '\n' + reply)
            return True
        except ValueError:
            logging.warning(a_device['host'] + ' Secret Password error')
        except NetMikoTimeoutException:
            logging.warning(a_device['host'] + ' Cannot connect to device,Please check if the network is communicating properly')
        except NetMikoAuthenticationException:
            logging.warning(a_device['host'] + ' Logon failure, incorrect username or password')

    'Definition do_cmd function,Used to execute commands'
    def do_cmd(self,cmds):
        'Read the file, for Statement loop execution command'
        with open(cmds) as cmd_obj:
            for cmd in cmd_obj:
                reply = self.ssh.send_command(cmd)
                time.sleep(2)
                logging.warning('>' * 10 + cmd.rstrip() + ' The command execution results are as follows:' + '>' * 10 + '\n' + reply)
    'Definition logout_host Function, close program'
    def logout_host(self):
        self.ssh.disconnect()

if __name__ == '__main__':
    cmds = 'cmd.txt'  # Store Execution Command File, Relative Path
    ssh_client = SSH_Client()
    start_time = datetime.now()
    for a_device in devices:
        'If the login result is True,Execute the command and exit'
        if ssh_client.login_host(a_device):
            ssh_client.do_cmd(cmds)
            ssh_client.logout_host()
            time.sleep(2)
    stop_time = datetime.now()
    print('Total time spent:{0}\n'.format(stop_time - start_time))

3. Operation effect

4. Error Reporting Effect

4.1 Unable to connect remotely

4.2 Error in username and password

5. Fragments

Combining the two articles, it is assumed that everyone knows how to use python to telnet or SSH network devices using its own library or a third-party library. However, you may ask, if the device contains multivendor, network device telnet and ssh, and many network devices, how can the code be optimized?Indeed, to solve a series of problems, let's do it one by one, and also let the beginners get familiar with it slowly. In the following articles, I will explain how to use multi-process and multi-threading to optimize, complete version of network inspection.
My code is not deep enough. Thank you for your comments.

If you like my article, please pay attention to my public number: drip technology, scanner attention, share it regularly

If you like my article, please pay attention to my public number: drip technology, scanner attention, share it regularly

Posted by sparrrow on Sat, 28 Sep 2019 06:13:23 -0700