Establishing the SSH Connection

Python 3: Automating Your Job Tasks Superhero Level: Automate Network Tasks with Python 3
13 minutes
Share the link to this page
Copied
  Completed
You need to have access to the item to view this lesson.
One-time Fee
$99.99
List Price:  $139.99
You save:  $40
€93.41
List Price:  €130.79
You save:  €37.37
£79.90
List Price:  £111.86
You save:  £31.96
CA$137.16
List Price:  CA$192.03
You save:  CA$54.87
A$153.08
List Price:  A$214.33
You save:  A$61.24
S$135.90
List Price:  S$190.27
You save:  S$54.36
HK$781.66
List Price:  HK$1,094.36
You save:  HK$312.69
CHF 91.23
List Price:  CHF 127.73
You save:  CHF 36.49
NOK kr1,107.76
List Price:  NOK kr1,550.92
You save:  NOK kr443.15
DKK kr696.86
List Price:  DKK kr975.63
You save:  DKK kr278.77
NZ$168.60
List Price:  NZ$236.05
You save:  NZ$67.44
د.إ367.24
List Price:  د.إ514.16
You save:  د.إ146.91
৳10,972.60
List Price:  ৳15,362.09
You save:  ৳4,389.48
₹8,346.11
List Price:  ₹11,684.89
You save:  ₹3,338.77
RM475.54
List Price:  RM665.78
You save:  RM190.23
₦123,487.65
List Price:  ₦172,887.65
You save:  ₦49,400
₨27,846.85
List Price:  ₨38,986.71
You save:  ₨11,139.85
฿3,694.58
List Price:  ฿5,172.56
You save:  ฿1,477.98
₺3,236.41
List Price:  ₺4,531.11
You save:  ₺1,294.69
B$519.35
List Price:  B$727.11
You save:  B$207.76
R1,861
List Price:  R2,605.48
You save:  R744.47
Лв182.73
List Price:  Лв255.83
You save:  Лв73.10
₩137,535.16
List Price:  ₩192,554.72
You save:  ₩55,019.56
₪374.71
List Price:  ₪524.61
You save:  ₪149.90
₱5,763.02
List Price:  ₱8,068.46
You save:  ₱2,305.43
¥15,525.12
List Price:  ¥21,735.79
You save:  ¥6,210.67
MX$1,695.96
List Price:  MX$2,374.42
You save:  MX$678.45
QR364.20
List Price:  QR509.89
You save:  QR145.69
P1,420.18
List Price:  P1,988.32
You save:  P568.13
KSh13,372.99
List Price:  KSh18,722.73
You save:  KSh5,349.73
E£4,798.26
List Price:  E£6,717.75
You save:  E£1,919.49
ብር5,719.92
List Price:  ብር8,008.12
You save:  ብር2,288.20
Kz83,641.63
List Price:  Kz117,101.63
You save:  Kz33,460
CLP$96,028.39
List Price:  CLP$134,443.59
You save:  CLP$38,415.20
CN¥723.89
List Price:  CN¥1,013.48
You save:  CN¥289.58
RD$5,819.58
List Price:  RD$8,147.64
You save:  RD$2,328.06
DA13,455.35
List Price:  DA18,838.03
You save:  DA5,382.68
FJ$226.17
List Price:  FJ$316.65
You save:  FJ$90.48
Q777.12
List Price:  Q1,088.01
You save:  Q310.88
GY$20,929.88
List Price:  GY$29,302.67
You save:  GY$8,372.79
ISK kr14,022.59
List Price:  ISK kr19,632.19
You save:  ISK kr5,609.60
DH1,011.06
List Price:  DH1,415.53
You save:  DH404.46
L1,768.33
List Price:  L2,475.73
You save:  L707.40
ден5,750.59
List Price:  ден8,051.06
You save:  ден2,300.46
MOP$805.69
List Price:  MOP$1,128
You save:  MOP$322.31
N$1,863.42
List Price:  N$2,608.86
You save:  N$745.44
C$3,672.13
List Price:  C$5,141.13
You save:  C$1,469
रु13,425.24
List Price:  रु18,795.88
You save:  रु5,370.63
S/376.35
List Price:  S/526.91
You save:  S/150.55
K385.89
List Price:  K540.26
You save:  K154.37
SAR375.01
List Price:  SAR525.03
You save:  SAR150.02
ZK2,677.10
List Price:  ZK3,748.04
You save:  ZK1,070.94
L464.84
List Price:  L650.79
You save:  L185.95
Kč2,347.91
List Price:  Kč3,287.17
You save:  Kč939.26
Ft36,370.18
List Price:  Ft50,919.71
You save:  Ft14,549.52
SEK kr1,092.76
List Price:  SEK kr1,529.91
You save:  SEK kr437.15
ARS$87,614.14
List Price:  ARS$122,663.30
You save:  ARS$35,049.16
Bs690.85
List Price:  Bs967.22
You save:  Bs276.36
COP$390,329.27
List Price:  COP$546,476.60
You save:  COP$156,147.32
₡51,017.42
List Price:  ₡71,426.43
You save:  ₡20,409.01
L2,476.75
List Price:  L3,467.55
You save:  L990.79
₲749,236.02
List Price:  ₲1,048,960.40
You save:  ₲299,724.38
$U3,833.15
List Price:  $U5,366.56
You save:  $U1,533.41
zł404.64
List Price:  zł566.52
You save:  zł161.87
Already have an account? Log In

Transcript

Hey, welcome to this lecture. First, let's scroll up to the beginning of this module, the SSH connection dot p y module. And notice a few things here. There are three Python built in modules that we haven't yet used inside this section of the course. The first one is bare amico. This is a non default Python module that will perform the SSH operations on each of our devices.

This is by far the most popular Python module when it comes to remote network connections via SSH. So since this isn't a built in Python module, we should install it as we did earlier in the course in the functions and modules section. To do that, let's open up the windows command line and use the PIP software package manager to install this module. First, you should make sure you're connected to the Internet, and then you should type in Python dash m, pip install and the name of the module Param eco. I already have this module installed. However, you should pause the video and install it on your own computer.

And then let's check if it was successfully installed by opening up the Python interpreter and importing the module. So this is the interpreter. Let's try import Param eco. Okay, no errors have been returned. So this works just fine. Also, going back to the top of our SSH connection.pi module, notice that we're also going to use the time module right here to insert some waiting times while Param eco does its job, and also the ar e module in order to search for any error messages that the switch might generate while executing the command we're sending.

Don't worry, we will discuss everything in detail in this video. Now let's focus on the code and scroll down to the SSH connection function. As you can see right from the start, this function takes an IP address as a public parameters so we have SSH connection of IP. Next we have to import the global variables from above user file, and CMD file. So these two variables right here, we are importing these two variables from the global namespace into the local namespace of the SSH connection function. And of course, as we've already discussed in the lecture about namespaces, we are using the global keyword to make the variables available inside the function.

As you can see, the code inside the function is wrapped inside the try except block. So this is the try clause. And down below we have the except clause. The difference from any try except blocks that we've seen so far is that this time the except clause covers or non built in exception, which belongs to the Param eco module and it is called authentication exception. This is raised when the wrong credentials are used for establishing the connection. Now, let's go back up to the Top of the function.

So first we are going to read the user name and password from a text file, the file referenced by user file. So it's now time to go ahead and create that file. I have already created it. And this is it right here, having the username, a comma, and then the password. Now it's time for you to do the same create your own file and save it in the same folder as the rest of the modules. Next, going back to the code.

These lines of code right here are meant for opening the file for reading and ensuring that the cursor is positioned at the beginning of the file each time we run the application using the seek method. Next, I use the read lines method to obtain a list where each element is a line in the file, and then the split and our strip string methods. to separate the user from the password, strip the newline character and extract the user name from that line. I used index zero because it refers to the first element in the list generated by the redlines method. In our case, Python will return a list with a single element, because we have only one line inside the file. Actually, to better understand what I did here, let's go into the Python interpreter and create a list that is identical to the one we are going to obtain from the red lines method.

So let me open up the interpreter. So this would be the list with a single element that the read lines method will return. Actually, to be more precise, this is the exact line we have inside the file. Okay. Now to extract the username, we should refer to the first and only element in this list that will have index zero, right? So a of zero will extract the string from within the list.

Good. Now, let's extract the username part of this string, but how? Well as already mentioned, the first step is to split the string using a separator and that separator is the comma of Of course, so we should apply the split method on a zero, a zero dot split using the comma. And this operation returns another list, with each element being one of the strings that were previously separated by comma. Now the final step is to extract the desired string from this list. And since we want the user name, that would be the first element, so we should just add the index zero.

And indeed, we got our username, the same procedure applies for extracting the password. Only this time, we should use index one to get the second element of the list. So let's try this. And indeed, we get Python in return. Also going back to the code, notice that I also added the our strip method for both the username and the password to avoid catching any newline characters in the string that we are extracting. That could give you some headaches when trying to connect to the device.

Trust me. I've been through this and it's not that Upon. Next, it's time to open an SSH connection to the Arista device. This is done by invoking the SSH client class from within the Param. Eco module, and also using a variable that I named session to refer to the SSH session being opened. Now the next line of code should be used cautiously.

So I'm referring to this line right here. It can allow or deny host keys from unknown remote servers, and save them to the host file of your system and thus causing some security concerns within your environment. Since we are developing an automation focused application, and we are in a test network, we can set this to auto add policy and accept any keys without interrupting the session. However, in a production environment, you may want to restrict accepting connections only for a predetermined set of hosts or for all hosts. Either way, don't forget to add this line to your code before the lines defining The actual connection to the device. I have attached a link to this lecture referencing Param equals official documentation for more information.

Okay, now looking at the next line of code inside this function, this line simply starts the connection to the IP address provided as an argument when calling the function using the credentials that Python reads from the text file we previously created. Also, as a safety measure, I have used the R st method again, to avoid any issues when opening the connection. A simple backslash n can make everything fail. As soon as the connection is established, we should create an object that I named connection which invokes an interactive shell session on the device meaning it reaches for the COI the command line interface of the switch. For this, we will use the invoke shell method applied on our newly created session as I did right here. So connection equals session dot invoke shell.

The next slide lines of code are params equals way of sending commands to the device. So we're using the standard method applied on the connection object and in between parentheses, we enter the COI command followed by a newline character just to make sure it gets executed and enclosed Of course, by single or double quotes. After entering the Enable mode of the switch using the Enable command, we are also setting the terminal length to zero to disable pagination, and have the entire output returned. In the case of show commands that return a long output like for instance, show running config. Next, we can also go further and enter the global configuration mode. In case we want to send not only show commands to the switch, but also configuration commands.

Now it's time for our module to grab the commands that should be sent to the Arista switches. So we're opening that specific text file for reading, as always using the open function right here. And of course, we will make sure that we are reading from the very beginning of the file using the seek method. As always, by the way, this is the file I have created for the commands to be sent to the switches. In my case, I have only a single show command show IP interface brief, you will enter one command per line inside this file. So you can pause the video right now and create your own file in which you will specify the commands going back to the code and scrolling down a bit.

So next using a for loop we are iterating over the list generated by the red lines method applied on the text file holding the commands. And for each command in the file. We are using the same sent method to send it over to the device. You might have noticed already each time I send the command to the device. I'm also using the sleep method as you can see right here for instance, from within the time module to allow the commands to be sent. Give the switch one or two seconds to respond to my request.

Finally, you should always remember to close your files once you finish working with them to avoid any issues within your running processes. So, we are closing both the user file and the CMD file after we finish working with each of them. Of course, if you want to see the output returned by this device, in case you're running a show command, maybe Param. Eco allows you to do that using the RCV method for the current connection. You can also specify how many bytes of data you want to receive back from the device, in our case, 65535, which I think is the maximum value for this argument. Of course, you can store this output using a variable for further use, like for instance, printing it to the screen, which we're going to do below.

Next, we are using an if else called block that checks for errors that have been generated by the device maybe as a consequence of a syntax error in one of the commands we sent. So, using an IF block and the search method from within the RV module for pattern matching, we are telling the application how to react. If that error message, namely invalid input is found anywhere in the output we receive from the device, then the user is notified that something went wrong using this print function right here, and also referencing the IP address of the device. This is easily done by simply using string formatting and the IP variable referring to the device we currently have an SSH connection open to. Otherwise, we print out a confirmation message to the screen, saying that the commands were sent successfully. If you would like to see the output returned by the device printed out to the screen, I added the print function right here displaying this output.

Otherwise, you can just comment this line using the hashtag sign and then save the file. So if you don't want to print the output of this Just use the hashtag sign to comment out this line, and then save the file. Finally, don't forget to close the session the SSH session using the close method applied on the session object. And now you're done. The last thing we should do is define the except statement corresponding to the try statement at the beginning of this function. The except clause states that if one authentication exception is raised by Param, eco inside the try block, then the user should be notified that something went wrong at login.

Basically, there may be two reasons for this. Either the text file contains an incorrect username or password, or the username and password have not been configured on the device using the username admin secret Python command. Okay, so basically that's it. That's the SSH connection dot p y module that takes care of a couple of verifications reads the username and password from the file opens the SSH connection sends commands receives the output and saves it for later use. I'll see you in the next lecture to discuss the last custom module that we will need for our final application. So I'll see you soon

Sign Up

Share

Share with friends, get 20% off
Invite your friends to LearnDesk learning marketplace. For each purchase they make, you get 20% off (upto $10) on your next purchase.