python server operation (b)

Get the server information, and writes excle

import paramiko
from openpyxl import Workbook
import time

# 操作Linux服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.12.1.212',22,'root','openailab')

'''
info的格式如下:
['total', 'used', 'free', 'shared', 'buff/cache', 'available',
'Mem:', '11G', '9.7G', '658M', '20M', '1.6G', '1.6G',
'Swap:', '0B', '0B', '0B']
'''

# 初始化
headerMem = ['total', 'used', 'free', 'shared', 'buff/cache', 'time'] # mem表头
headerSwap = ['total', 'used', 'free', 'time'] # swap表头
wb = Workbook()
ws1 = wb.create_sheet("Men")
ws2 = wb.create_sheet("Swap")
ws1.append(headerMem)
ws2.append(headerSwap)
t = 10 # 隔t秒写入数据
# 写入数据
while 1:
    # stdout 为正确输出,stderr为错误输出(只返回一个错误),stdin为从键盘读取信息
    # 终端(Terminal)的标准输入(standard input),标准输出( standard out)和标准错误输出(standard error)
    stdin, stdout, stderr = ssh.exec_command('free -h') # 服务器上执行指令
    err = stderr.read().decode()
    if len(err) != 0:
        print(err)
    else :
        pass
        f = stdout.read().decode() # utf-8编码读取打印内容
        # print(stdout.readlines()) # 明明有数据,为什么读出来为空?因为上一个语句已经读出
        info = f.split() # 将字符串空格去掉,转化成列表形式
        mems = info[7:12] # 获取mem数据
        swaps = info[14:17] # 获取swap数据
        creatTime = time.strftime("%Y-%m-%d %H:%M:%S") # 格式化时间
        mems.append(creatTime) # 在mem列表中加入时间
        swaps.append(creatTime) # 在swaps列表中加入时间
        ws1.append(mems) # mem每行添加数据
        ws2.append(swaps) # swaps每行添加数据
    wb.save("./memoryInfo.xlsx")
    time.sleep(t)

Published 25 original articles · won praise 0 · Views 2679

Guess you like

Origin blog.csdn.net/weixin_43431593/article/details/103914890