python分析服务器日志_python读取服务器日志

1. 代码

import paramiko

def get_server_log():

hostname = ""

port = 22

username = ""

password = ""

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(hostname, port, username, password, compress=True)

sftp_client = client.open_sftp()

remote_file = sftp_client.open("/opt/xxx/logs/error_log")

try:

count = 0

for line in remote_file:

if 'Traceback' in line:

print(line)

count = count + 1

print(count)

finally:

remote_file.close()

if __name__ == "__main__":

get_server_log()

print('****done')

2. 验证Traceback在日志文件出现次数

grep -F "Traceback" -R logs/error_log

3. 普通用户登录时可能报sftp权限错误,可以先给改目录分配用户权限

chown -R username:username logs/error_log

4. 如果不方便使用chown授权,但是可以当你用普通账号登录后可以切换成root用户,也可以这样写(就是sudo切换一下):

client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect(hostname, port, username, password, compress=True)

if username != 'root':

ssh = client.invoke_shell()

time.sleep(0.1)

ssh.send('sudo su \n')

buff = ''

while not buff.endswith('Enter domain (xxx) password:'): # 这里改成你自己的

resp = ssh.recv(9999)

buff += resp

ssh.send(password)

ssh.send('\n')

buff = ''

while not buff.endswith('# '):

resp = ssh.recv(9999)

buff += resp

ssh.send(remote_command)

ssh.send('\n')

buff = ''

while not buff.endswith('# '):

resp = ssh.recv(9999)

buff += resp

client.close()

result = buff

else:

stdin, stdout, stderr = client.exec_command(remote_command)

result = stdout.read()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值