Python SSH

Hi Azm,

Let’s see if I can help you out. First of all, I understand the confusion…I ran into the same issues when I learned Python for the first time.

I would advise becoming very familiar with “basic” python scripts first. It’s so much easier when you only have to deal with your own code instead of third party libraries.

Try creating a module on your own first that you import, that might help to understand things.

Having said that, let’s take a look.

With these import lines, we import the “ConnectHandler” function from the netmiko library and the “getpass” function from the getpass library. Here’s an explanation with the differences between importing an entire module vs importing a function of a module:

Now the big question is, what is the “ConnectHandler” function from netmiko? Looking at the examples:

It seems that this is a function that establishes the connection through SSH. If you really wanted to know, you could dive into the netmiko code. Searching for “def ConnectHandler” I find this:

Looking at the code, we can see that the ConnectHandler function calls another function (ssh_dispatcher). Now you could dive into netmiko further and further, you shouldn’t. This will be a rabbit hole with no end. The goal of using a library like netmiko is to abstract away the complexity of connecting with SSH, making it possible to connect to a device with only a few lines of code in your own script.

What about the getpass function? Let’s check the documentation:

https://docs.python.org/2/library/getpass.html

Their documentation explains it well:

The getpass module provides two functions:

getpass.getpass([prompt[, stream]])

Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows).

So when you see this in Python code, people use it so that when a user types the password, it doesn’t show up on your screen.

When you use any third-party libraries, I would always suggest checking the documentation. Popular libraries have good documentation with examples and explanations. Youtube videos can be useful but you still want to know what you are doing in your own code.

There are two ways to execute Python code, there’s a detailed explanation here:

  1. You type Python code in the Interpreter which you recognize with the >>> symbols.
  2. You run Python scripts from the command-line with “python .py”

The interpreter is useful when you want to test something quickly, otherwise, it’s so much easier to write a .py file and execute it.

This example of netmiko is a good start:

They execute this code for a single network device. You could use a Python for loop to execute this for multiple devices:

I hope this helps!

Rene