Search code examples
pythonpython-3.xoutputspecial-charactersparamiko

Get rid of ['\n'] in python3 with paramiko


I've just started to write a monitoring tool in Python 3, and I'm wondering if I can get a 'clear' number output through ssh. I've written this script:

import os
import paramiko

command = 'w|grep \"load average\"|grep -v grep|awk {\'print ($10+$11+$12)/3*100\'};'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy())
ssh.connect('10.123.222.233', username='xxx', password='xxx')
stdin, stdout, stderr = ssh.exec_command(command)
print (stdout.readlines())
ssh.close()

It works fine, except the output is:

['22.3333\n']

How can I get rid of the [' and \n'] and just get the clear number value?

How can I get the result as I see it in PuTTy?


Solution

  • .readlines() returns a list of separate lines. In your case there is just one line, you can just extract it by indexing the list, then strip of the whitespace at the end:

    firstline = stdout.readlines()[0].rstrip()
    

    This is still a string, however. If you expected numbers, you'd have to convert the string to a float(). Since your command line will only ever return one line, you may as well just use .read() and convert that straight up (no need to strip, as float() is tolerant of trailing and leading whitespace):

    result = float(stdout.read())