__main__.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env python
  2. """
  3. smart-top, The Phi Technology LLC
  4. Steve L. Nyemba & Michael Meade
  5. The smart-top is a utility that enables to monitor processes (among other things) and use the data for:
  6. - detecting anomalies
  7. -
  8. """
  9. import smart.top
  10. import pandas as pd
  11. import sys
  12. import os
  13. import re
  14. import time
  15. import numpy as np
  16. # df = pd.DataFrame (smart.top.read(name='firefox,code'))
  17. HOME_FOLDER = os.environ['HOME']
  18. SYS_ARGS = {}
  19. if len(sys.argv) > 1:
  20. N = len(sys.argv)
  21. for i in range(1,N):
  22. value = None
  23. if sys.argv[i].startswith('--'):
  24. key = sys.argv[i][2:] #.replace('-','')
  25. SYS_ARGS[key] = 1
  26. if i + 1 < N:
  27. value = sys.argv[i + 1] = sys.argv[i+1].strip()
  28. if key and value and not value.startswith('--'):
  29. SYS_ARGS[key] = value
  30. i += 2
  31. if __name__ == '__main__' :
  32. try:
  33. if 'help' in SYS_ARGS :
  34. print (help_me)
  35. sys.exit(0)
  36. if 'watch' in SYS_ARGS :
  37. SYS_ARGS['watch'] = int(SYS_ARGS['watch'])
  38. if SYS_ARGS['watch'] <= 1 :
  39. SYS_ARGS['watch'] = 10
  40. log = pd.DataFrame()
  41. while True:
  42. os.system('clear')
  43. print ()
  44. print ("================================= SMART TOP ================================= ")
  45. print ()
  46. df = pd.DataFrame()
  47. if 'folder' in SYS_ARGS :
  48. for path in SYS_ARGS['folder'].split(',') :
  49. df = df.append(smart.folder.read(path=path))
  50. cols = df.columns.tolist()
  51. else:
  52. df = smart.top.read()
  53. cols = ['pid','name','user','cpu','mem','started','date','time','status']
  54. for key in SYS_ARGS :
  55. value = SYS_ARGS[key]
  56. if not value or key not in df.columns:
  57. continue
  58. ii = df.apply(lambda row:re.match(value,str(row[key])) is not None,axis=1)
  59. df = df[ii].copy()
  60. df.index = np.arange(df.shape[0])
  61. # df = pd.DataFrame(smart.top.read(name='fire'))
  62. log = log.append(df)
  63. if not df.empty :
  64. print (df[cols])
  65. if 'watch' in SYS_ARGS :
  66. time.sleep(SYS_ARGS['watch'])
  67. else:
  68. break
  69. except KeyboardInterrupt:
  70. if 'log' in SYS_ARGS :
  71. file = 'smart-top.csv' if SYS_ARGS['log'] == 1 else SYS_ARGS['log']
  72. log[['name','cmd','cpu','mem','started','date','time','status','node']].to_csv(file,index=False)
  73. print ()
  74. print ("... Exiting, Thanks for using smart-top")
  75. # pass
  76. # print (df.groupby(['user'])['cpu','mem'].sum())