利用python实现自动捕获进程netstat信息和自动捕获telnet信息,保存log文件
程序员文章站
2022-04-09 21:21:21
...
利用python实现自动捕获进程netstat信息和自动捕获telnet信息,保存log文件
*采用subprocess类,实现执行shell命令,捕获netstat、pstack、maps等进程重要数据,保存到log文件
*采用libtelnet库登录telnet
*捕获telnet输出到log文件
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AUTH: [email protected]
tag: telnet ,then execute all of the API,and capture the print line writing to file;
Local only
"""
import telnetlib
import subprocess
import re
import sys
import time
import socket
from sys import argv
exename = 'test'
filename = './testlogflush.log'
apilist = ['version', 'help']
arglist = argv[1:] # 支持传参
def conscmd(): #要执行的系统shell命令
'''
:return: all the shell cmdline
'''
global cmdlist
# 0 and 1 is inner cmd
cmdlist.append('ps -aux| grep /{}| grep -v grep'.format(exename))
cmdlist.append( 'netstat -pnlt| grep {}'.format(exename) )
#following lines, is user define
cmdlist.append('ps -aux| grep /{}'.format(exename))
cmdlist.append( 'netstat -apn| grep {}'.format(exename) )
cmdlist.append( 'df -h' )
exepid = filtcmdline(cmdlist[0])
if exepid:
cmdlist.append( 'ps -o comm,lstart -p {}'.format(exepid) )
cmdlist.append( 'top -bHp {} -n 3'.format(exepid) )
cmdlist.append( 'pstack {}'.format(exepid) )
cmdlist.append('cat /proc/{}/task/*/stat'.format(exepid))
cmdlist.append('cat /proc/{}/maps'.format(exepid))
cmdlist.append('cat /proc/{}/smaps'.format(exepid))
def getlocalhostip(): #获取本机ip
'''
get the local ip address
:return:
'''
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
except:
print(sys._getframe().f_code.co_name, '() captured except ', sys.exc_info()[0], sys.exc_info()[1])
finally:
s.close()
return ip
def execcmd(cmd): #执行系统shell命令
'''
:param cmd: ssh cmd
:return: the cmd result(bytes of list)
'''
try:
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
time.sleep(0.1) # waited subprocess end
if proc.poll() != None:
print( "executed cmd: {0} .error= {2}, subprocess.Popen-poll() = {1}".format(cmd, proc.poll(), proc.stdout.readlines()) )
proc.terminate()
return None
else:
cmdline = proc.stdout.readlines() # list bytes
print( "executed cmd: {0} .OK".format(cmd) )
return cmdline
except :
print(sys._getframe().f_code.co_name, '() captured except ', sys.exc_info()[0], sys.exc_info()[1])
raise
return None
def filtcmdline(cmd, cmdtype='pid'):
'''
get the LISTEN port of telnet
:param cmd:
:param cmdtype: 'pid' or 'telnetport'
:return: program's telnet port, named exename
'''
try:
cmdret = execcmd(cmd )
if cmdret:
reline = ''
if cmdtype == 'pid':
reline = r'\b\d{3,7}\b'
elif cmdtype == 'telnetport':
reline = r'0.0.0.0:2\d\d\d\b'
strret = re.search(reline, str(cmdret.pop(), encoding='utf-8'))
if strret:
return int( strret.group().split(":").pop() )
else:
print("re.match error")
else:
print("fun: {} execute execcmd() failed".format(sys._getframe().f_code.co_name))
except :
print(sys._getframe().f_code.co_name, '(), captured except ', sys.exc_info()[0], sys.exc_info()[1])
return 0
def execapi(teln): # 执行进程telnet中的api命令
'''
:param teln: the handle of telnet's connection
:return:
'''
try:
teln.read_until(b"Username:")
teln.write(b'admin\r\n')
teln.read_until(b"Password:")
teln.write(b'admin\r\n')
teln.write(b'\r\n' * 4)
for cd in apilist:
teln.write(bytes(cd,encoding = "utf8")+b'\r\n')
time.sleep(0.5)
except:
print(sys._getframe().f_code.co_name, '(), captured except ', sys.exc_info()[0], sys.exc_info()[1])
raise
def logtelnet(flog): #telnet到进程服务
'''
telnet to mcu
:param flog: logfile's handle
:return:
'''
mcuport = filtcmdline(cmdlist[1], 'telnetport')
if mcuport:
try:
tn = telnetlib.Telnet('127.0.0.1', mcuport)
execapi(tn)
# print("logtelnet: {}".format(tn.read_very_eager().decode('gbk')))
flog.write(tn.read_very_eager() + b'\r\n' * 3)
except:
print(sys._getframe().f_code.co_name, '(), captured except ', sys.exc_info()[0], sys.exc_info()[1])
finally:
tn.close()
else:
print("error telnetport: ",mcuport)
return False
return True
def logcmddict(flog):
'''
capturing all cmd stdoutline
:param flog: the logfile handle
:return:
'''
localip = getlocalhostip()
for v in cmdlist[2:]:
time.sleep(0.5)
cmdret = execcmd(v)
if cmdret: # print("cmdkey: {}".k))
flog.write(bytes('[[email protected] {}]# '.format(localip)+ v, encoding='utf-8')+b'\n')
for i in cmdret:
flog.write(i)
flog.write(b'\n' * 3)
else:
print('executed cmdline failed')
def writinglog(): # 写文件
'''
:return:
'''
with open(filename, 'wb') as fl:
logtelnet(fl)
logcmddict(fl)
cmdlist = []
if __name__ == "__main__":
conscmd()
writinglog()
上一篇: JS之consloe.log()
下一篇: console.log 调试强大应用