Python实践(一)——paramiko监控日志

# Python实践(一)——paramiko监控日志

一、功能

  1. 使用paramiko打开ssh连接远程服务器
  2. tail命令监控服务器上某日志文件
  3. 日志文件中出现期望的文字,停止日志文件监控
  4. 执行相关命令

二、实现

代码如下(示例):

import sys
import traceback
import paramiko
import time
from paramiko_expect import SSHClientInteraction

etx = '\x03'

host = "192.168.3.189"
sshport = 22
uname = 'root'
pwd = 'root'
prompt = '.*]#.*'
filepath = '/dev/shm/err.log'
msg_expect = 'xpro-ns ready for test! gogo...'
time_signalling = 2

# 自行修改输出函数
json_list = []


def output_func(msg):
    sys.stdout.write(msg)
    json_list.append(msg)
    sys.stdout.flush()

def stop_func(msg):
    if msg_expect in msg:
        return True

def signalling_send(path):
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, port=sshport, username=uname, password=pwd)
        interact = SSHClientInteraction(client, timeout=10, display=False)
        interact.send('\n')
        interact.expect(prompt)
        cmd = 'tailf %s' % path
        print(cmd)
        interact.send(cmd)
        interact.tail(output_callback=output_func, stop_callback=stop_func, timeout=60)
    except KeyboardInterrupt:
        print('Ctrl+C interruption detected, stopping tail')
        print(interact.current_output)
    except Exception:
        traceback.print_exc()
    finally:
            pass

    time.sleep(time_signalling)
    print('Send Ctrl+C to interrupte err.log file')
    interact.send(etx)
    time.sleep(time_signalling)
    interact.expect(prompt)
    interact.send('cd /home/ns/tools/mcisim\n')
    interact.expect(prompt)
    print('Send signaling: ./udp_media_attach -f udp_media_attach.cfg_ipv4')
    interact.send('./udp_media_attach -f udp_media_attach.cfg_ipv4\n')
    time.sleep(time_signalling)
    client.close()


if __name__ == '__main__':
    signalling_send(filepath)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值