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
€92.01
List Price:  €128.82
You save:  €36.80
£78.62
List Price:  £110.08
You save:  £31.45
CA$136.30
List Price:  CA$190.82
You save:  CA$54.52
A$149.91
List Price:  A$209.88
You save:  A$59.97
S$134.67
List Price:  S$188.54
You save:  S$53.87
HK$780.27
List Price:  HK$1,092.41
You save:  HK$312.14
CHF 90.94
List Price:  CHF 127.32
You save:  CHF 36.38
NOK kr1,066.52
List Price:  NOK kr1,493.17
You save:  NOK kr426.65
DKK kr686.58
List Price:  DKK kr961.24
You save:  DKK kr274.66
NZ$163.87
List Price:  NZ$229.42
You save:  NZ$65.55
د.إ367.25
List Price:  د.إ514.17
You save:  د.إ146.91
৳11,719.12
List Price:  ৳16,407.24
You save:  ৳4,688.11
₹8,330.23
List Price:  ₹11,662.65
You save:  ₹3,332.42
RM469.20
List Price:  RM656.90
You save:  RM187.70
₦150,315.07
List Price:  ₦210,447.11
You save:  ₦60,132.04
₨27,850.73
List Price:  ₨38,992.14
You save:  ₨11,141.40
฿3,630.46
List Price:  ฿5,082.79
You save:  ฿1,452.33
₺3,219.70
List Price:  ₺4,507.71
You save:  ₺1,288.01
B$510.41
List Price:  B$714.60
You save:  B$204.18
R1,812.12
List Price:  R2,537.04
You save:  R724.92
Лв179.93
List Price:  Лв251.91
You save:  Лв71.98
₩136,185.36
List Price:  ₩190,664.95
You save:  ₩54,479.59
₪367.41
List Price:  ₪514.40
You save:  ₪146.98
₱5,821.06
List Price:  ₱8,149.72
You save:  ₱2,328.66
¥15,620.48
List Price:  ¥21,869.30
You save:  ¥6,248.82
MX$1,652.93
List Price:  MX$2,314.17
You save:  MX$661.24
QR364.95
List Price:  QR510.95
You save:  QR145.99
P1,352.36
List Price:  P1,893.35
You save:  P540.99
KSh13,173.68
List Price:  KSh18,443.68
You save:  KSh5,270
E£4,665.55
List Price:  E£6,531.96
You save:  E£1,866.40
ብር5,748.74
List Price:  ብር8,048.47
You save:  ብር2,299.72
Kz84,841.51
List Price:  Kz118,781.51
You save:  Kz33,940
CLP$89,061.09
List Price:  CLP$124,689.09
You save:  CLP$35,628
CN¥708.59
List Price:  CN¥992.06
You save:  CN¥283.46
RD$5,854.95
List Price:  RD$8,197.17
You save:  RD$2,342.21
DA13,441.70
List Price:  DA18,818.91
You save:  DA5,377.21
FJ$225.92
List Price:  FJ$316.30
You save:  FJ$90.37
Q777.53
List Price:  Q1,088.58
You save:  Q311.04
GY$20,937
List Price:  GY$29,312.64
You save:  GY$8,375.63
ISK kr13,829.61
List Price:  ISK kr19,362.01
You save:  ISK kr5,532.40
DH991.60
List Price:  DH1,388.28
You save:  DH396.68
L1,762.87
List Price:  L2,468.10
You save:  L705.22
ден5,662.62
List Price:  ден7,927.89
You save:  ден2,265.27
MOP$803.97
List Price:  MOP$1,125.59
You save:  MOP$321.62
N$1,822.52
List Price:  N$2,551.60
You save:  N$729.08
C$3,683.31
List Price:  C$5,156.79
You save:  C$1,473.47
रु13,336.33
List Price:  रु18,671.39
You save:  रु5,335.06
S/374.07
List Price:  S/523.71
You save:  S/149.64
K388.76
List Price:  K544.29
You save:  K155.52
SAR375.01
List Price:  SAR525.03
You save:  SAR150.01
ZK2,584.38
List Price:  ZK3,618.24
You save:  ZK1,033.85
L457.58
List Price:  L640.63
You save:  L183.05
Kč2,270.94
List Price:  Kč3,179.41
You save:  Kč908.46
Ft35,419.21
List Price:  Ft49,588.32
You save:  Ft14,169.10
SEK kr1,065.66
List Price:  SEK kr1,491.97
You save:  SEK kr426.30
ARS$88,866.21
List Price:  ARS$124,416.25
You save:  ARS$35,550.04
Bs691.54
List Price:  Bs968.19
You save:  Bs276.64
COP$383,048.62
List Price:  COP$536,283.39
You save:  COP$153,234.77
₡51,221.68
List Price:  ₡71,712.40
You save:  ₡20,490.72
L2,473.46
List Price:  L3,462.95
You save:  L989.48
₲749,179.97
List Price:  ₲1,048,881.93
You save:  ₲299,701.95
$U3,850.87
List Price:  $U5,391.37
You save:  $U1,540.50
zł391.42
List Price:  zł548.01
You save:  zł156.58
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.