简体   繁体   中英

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?

.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())

Instead of print(stdout.readlines()) you should iterate over each element in the list that is returned by stdout.readlines() and strip it, possibly converting it to float as well (depends what you are planning to do with this data later).

You can use list comprehension for this:

print([float(line.strip()) for line in stdout.readlines()])

Note that strip will remove whitespaces and new-line chars from both the start and end of the string. If you only want to remove the trailing whitespace/new-line char then you can use rstrip , but note that the conversion to float may then fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM