-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Python Network Programming Techniques
By :
With our connection now open, we can go ahead and execute a command on our remote device. Similar to the way we deal with issuing commands on a remote device by hand, we have three different streams that come back to us: the standard out (or stdout), which is the normal output, the standard error (or stderr), which is the default stream for the system to return errors on, and the standard in (or stdin), which is the stream used to send text back into the executed command. This can be useful if, in your workflow, you would normally interact with the command line.
In this recipe, you will see how to programmatically open an SSH connection and then send a command of your choice to the device.
Open your code editor and start by creating a file called command.py. Next, navigate your terminal to the same directory that you just created the command.py file in.
Let's start by importing the Paramiko library and create a client object as seen in the last recipe. We'll then execute a single command of your choice on this device:
from paramiko.client import SSHClient
SSH_USER = "<Insert your ssh user here>" SSH_PASSWORD = "<Insert your ssh password here>" SSH_HOST = "<Insert the IP/host of your device/server here>" SSH_PORT = 22 # Change this if your SSH port is different
SSHClient object, which we just imported from Paramiko: client = SSHClient()
connect method of the client object to do so. Before actually connecting, we will need to make sure that our client knows the host keys: client.load_system_host_keys() client.connect(SSH_HOST, port=SSH_PORT, username=SSH_USER, password=SSH_PASSWORD)
stdin, stdout, and stderr:CMD = "show ip interface brief" # You can issue any command you want stdin, stdout, stderr = client.exec_command(CMD) client.close()
python3 command.py
In this example, we first created a new client as seen in the previous example. We then used the exec_command() method to execute a command of our choice.
The function returns three different file-like objects for the three different streams: stdin, stdout, and stderr. In the next recipe, Reading the output of an executed command, we will use this to read back the output that was provided when executing a command.