Select Page

Saving the SSH command results – about 10 minutes

Way back in the beginning we talked about this project being able to save config info locally. And then we talked a bunch about databases, SSH connections, functions, and variables, but we haven’t actually saved anything locally yet. You probably didn’t fall for the smoke and mirrors, but other readers may have. Anyway, now to get to saving locally. Finally.

The bulk of the last iteration of the program remains the same. We’re making some modifications to the existing read_from_all_devices().

The gist of this evolution of the project is that we have added saving the results from the device to a text file on our local computer.

The function jumps right into something new with the try keyword. Python will execute all of the code that is inside the try block (indented under the try), but if it runs into any errors then Python will jump to the except statement and execute those lines of code. So, in this evolution if there is an error executing, say ssh.invoke_shell() then we’ll drop right into the except code and print out some [hopefully] useful error messages.

We’re adding a little more code here too in order to save our output to a text file. The file input/output happens in these lines of code:

First we are saving the filename that we want to a variable. Next we open() the file. The second parameter 'w' is an option telling Python to open the file for writing and to delete any file contents already present. To add content to the file we use a method in our f file object: f.write(). Easy peasy. After we write the text we make sure to close our file using f.close(). The close() will make sure that everything is saved on your local disk. What? Saved on your local disk??? Finally!

Share This