python运维篇---实时查看liunx后台日志(转)

发布时间 2023-11-21 16:45:12作者: 奋斗终生

原文:https://blog.51cto.com/u_12203282/6000840

作者:咪哥杂谈

为啥要用python去做实时监控linux后台日志呢,其实是因为在元旦监控生产环境时发现的诟病,服务器太多导致xshell一开窗口要开好多个,而现在又没有实现自动化运维的功能,不仅是这样,若想要查看某台服务器上的日志还需要先ctrl + c终止终端(terminal),而查看筛选条件也需要重复性的大量操作,于是想到有没有可以用python写个脚本连接到各台服务器上,监控的同时直接把日志写入到本地上。有了想法,实现只是时间问题咯。。。

环境

python3

linux的各种ip以及对应的账号密码
第三方库:paramiko
这里要说一下,windows下借助的第三方库是paramiko这个加密及SSH功能的强大库,推荐再有网的情况下进行安装:

pip install paramiko

 

代码实现

废话不多说,直接上码,注释写的很详细,老规矩不多讲:

import time
import paramiko
import select
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
now_day = time.strftime('%Y-%m-%d', time.localtime(time.time()))

#方法复用,连接客户端通过不同id进来即可
#这个方法是进行非实时的连接返回,例如ls这样的cmd命令,或者grep这样的命令。。
def link_server_cmd(serverip,user,pwd):
    print('------------开始连接服务器(%s)-----------' % serverip)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print('------------开始认证......-----------')
    client.connect(serverip, 22, username=user, password=pwd, timeout=4)
    print('------------认证成功!.....-----------')
    while 1:
        cmd = input('(输入linux命令)~:')
        stdin, stdout, stderr = client.exec_command(cmd)
        #enumerate这个写法可遍历迭代对象以及对应索引
        for i, line in enumerate(stdout):
            print(line.strip("\n"))
        break
    client.close()

#此方法是进行实时返回,例如tail -f这样的命令,本次监控就用的是此方法。
#将实时返回的日志返回到本地
def link_server_client2(serverip, user, pwd):
    # 进行连接
    print('------------开始连接服务器(%s)-----------' % serverip)
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    print('------------开始认证......-----------')
    client.connect(serverip, 22, username=user, password=pwd, timeout=4)
    print('------------认证成功!.....-----------')
    # 开启channel 管道
    transport = client.get_transport()
    channel = transport.open_session()
    channel.get_pty()
    # 执行命令nohup.log.2017-12-30
    tail = 'tail -f /xxxx/xxxxx/nohuplogs/nohuplogs20180101.log'
    #将命令传入管道中
    channel.exec_command(tail)
    while True:
        #判断退出的准备状态
        if channel.exit_status_ready():
            break
        try:
            # 通过socket进行读取日志,个人理解,linux相当于客户端,我本地相当于服务端请求获取数据(此处若有理解错误,望请指出。。谢谢)
            rl, wl, el = select.select([channel], [], [])
            if len(rl) > 0:
                recv = channel.recv(1024)
                # 此处将获取的数据解码成gbk的存入本地日志
                print(recv.decode('gbk', 'ignore'))
                text_save(recv.decode('gbk', 'ignore'), 'tail(' + serverip + ').txt')
        #键盘终端异常
        except KeyboardInterrupt:
            print("Caught control-C")
            channel.send("\x03")  # 发送 ctrl+c
            channel.close()
    client.close()

# 文件存储
def text_save(self,content, filename, mode='a'):
    # Try to save a list variable in txt file.
    file = open(filename, mode)
    for i in content:
        file.write(i)
    file.close()

结论

结果不言而喻呀,当然是成功了,这里因为涉及到隐私问题,就不上传生产的图片结果了,有需要的同学可以亲测一下,通过这次的代码需求,感觉对于自己监控而言,确实是方便了不少,在解决channel管道进行实时传输数据那里费时比较多…..因为对socket编程不是很了解,后续继续看看吧…