Paramiko capturing command output
<p>I have an issue that has been giving me a headache for a few days. I am using the Paramiko module with Python 2.7.10 and I'd like to issue multiple commands to a Brocade router, but only return output from one of the given commands like so:</p>

<pre><code>#!/usr/bin/env python
import paramiko, time

router = 'r1.test.example.com'
password = 'password'
username = 'testuser'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(router, username=username, password=password)
print('Successfully connected to %s' % router)

remote_conn = ssh.invoke_shell()
output = remote_conn.recv(1000)

# Disable paging on Brocade.
remote_conn.send('terminal length 0\n')
# Check interface status.
remote_conn.send('show interfaces ethernet 0/1\n') # I only want output from this command.
time.sleep(2)
output = remote_conn.recv(5000)
print(output)
</code></pre>

<p>If I were to print the full output it would contain everything issued to the router, but I only want to see output from the show <code>interfaces ethernet 0/1\n</code> command.</p>

<p>Can anyone help with this issue?</p>

<p>One final thing I would like to ask. I want to filter through the <code>output</code> variable and check for occurrences of strings like "up" or "down", but I can't seem to get it to work because everything in the output appears to be on new lines?</p>

<p>For example:</p>

<p>If I iterate over the <code>output</code> variable in a for loop I get all of the characters in the variable like so:</p>

<pre><code>for line in output:
    print(line)
</code></pre>

<p>I get an output like this:</p>

<p>t</p>

<p>e</p>

<p>r</p>

<p>m</p>

<p>i</p>

<p>n</p>

<p>a</p>

<p>l</p>

<p>l</p>

<p>e</p>

<p>n</p>

<p>g</p>

<p>t</p>

<p>h</p>

<p>0</p>

<p>Any way around this?</p>

<p>Again,</p>

<p>Thanks in advance for any help.</p>

<p>Best regards,</p>

<p>Aaron C.</p>

<p>If you can, the <code>exec_command()</code> call provides a simpler mechanism to invoke a command. I have seen Cisco switches abruptly drop connections that try <code>exec_command()</code>, so that may not be usable with Brocade devices.</p>

<p>If you must go the <code>invoke_shell()</code> route, be sure to clear all pending output after connecting and after <code>send('terminal length 0\n')</code>, checking <code>recv_ready()</code> before calling <code>recv()</code> to avoid blocking on reading data that might not ever arrive. Since you are controlling an interactive shell, <code>sleep()</code> calls might be needed to allow the server adequate time to process and send data, or it might be necessary to poll the output string to confirm that your last command completed by recognizing the shell prompt string.</p>

python python-2.7 ssh paramiko