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>For your second question: Though I am not specialist of paramiko, I see that function recv, <a href="http://docs.paramiko.org/en/2.0/api/channel.html" rel="nofollow">according to the doc</a>, returns a string. If you apply a <strong>for</strong> loop on a string, you will get characters (and not lines as one might perhaps expect). The newline is caused by your use of the print function as explained <a href="http://www.pythonlearn.com/html-008/cfbook007.html" rel="nofollow">on this page, at paragraph 6.3</a>.</p>

<p>I haven't studied what paramiko suggests to do. But why don't you treat the full string as a single entity? For example, you could check the presence of "up" as:</p>

<pre><code>if "up" in output:
</code></pre>

<p>Or, if that suits your needs better, you could <a href="http://stackoverflow.com/questions/172439/how-do-i-split-a-multi-line-string-into-multiple-lines">split the string into lines</a> and then do whatever test you want to do:</p>

<pre><code>for line in output.split('\n'): 
</code></pre>

python python-2.7 ssh paramiko