From 991936ff3eefb77e25753ffb29f0a85cc5ca9e83 Mon Sep 17 00:00:00 2001
From: Oleksii Shevchuk
Date: Thu, 16 Mar 2017 17:51:08 +0200
Subject: [PATCH] Add w command
---
pupy/modules/w.py | 67 +++++++++++++++++++++++++++++++++++++
pupy/packages/all/pupyps.py | 53 ++++++++++++++++++++++++++++-
2 files changed, 119 insertions(+), 1 deletion(-)
create mode 100644 pupy/modules/w.py
diff --git a/pupy/modules/w.py b/pupy/modules/w.py
new file mode 100644
index 00000000..017f2a0e
--- /dev/null
+++ b/pupy/modules/w.py
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+from pupylib.PupyModule import *
+from pupylib.PupyCmd import PupyCmd
+from pupylib.utils.rpyc_utils import obtain
+from pupylib.utils.term import colorize
+from modules.lib.utils.shell_exec import shell_exec
+from datetime import datetime, timedelta
+
+import logging
+
+__class_name__="WModule"
+
+ADMINS = ('NT AUTHORITY\SYSTEM', 'root')
+
+@config(cat="admin")
+class WModule(PupyModule):
+ """ list terminal sessions """
+
+ dependencies = [ 'pupyps' ]
+ is_module=False
+
+ def init_argparse(self):
+ self.arg_parser = PupyArgumentParser(prog="w", description=self.__doc__)
+
+ def run(self, args):
+ try:
+ data = obtain(self.client.conn.modules.pupyps.users())
+
+ tablein = []
+
+ for user, hosts in reversed(sorted(data.iteritems())):
+ for host, sessions in hosts.iteritems():
+ for session in sessions:
+ object = {
+ 'HOST': host,
+ 'USER': colorize(
+ user,
+ "yellow" if user in ADMINS else (
+ "green" if session.get('me') else "")
+ ),
+ 'LOGIN': str(datetime.fromtimestamp(int(session['started']))),
+ }
+
+ if session.get('terminal'):
+ if session.get('name'):
+ what = '{} {}'.format(
+ session['exe'] if session.get('exe') else ('{'+session.get('name')+'}'),
+ ' '.join(session['cmdline'][1:] if session.get('cmdline') else '')
+ )
+ else:
+ what = ''
+
+ object.update({
+ 'IDLE': str(timedelta(seconds=session['idle'])),
+ 'WHAT': what
+ })
+
+ tablein.append(object)
+
+ self.stdout.write((PupyCmd.table_format(tablein)))
+
+ except Exception, e:
+ logging.exception(e)
+
+
+
+
diff --git a/pupy/packages/all/pupyps.py b/pupy/packages/all/pupyps.py
index 3a931b19..a9737188 100644
--- a/pupy/packages/all/pupyps.py
+++ b/pupy/packages/all/pupyps.py
@@ -4,6 +4,8 @@ import psutil
import collections
import sys
+import os
+import time
def pstree():
data = {}
@@ -51,5 +53,54 @@ def pstree():
return min(tree), tree, data
+def users():
+ info = {}
+ me = psutil.Process()
+ terminals = {}
+
+ if hasattr(me, 'terminal'):
+ for p in psutil.process_iter():
+ pinfo = p.as_dict(['terminal', 'pid', 'exe', 'name', 'cmdline'])
+ if pinfo.get('terminal'):
+ terminals[pinfo['terminal'].replace('/dev/', '')] = pinfo
+
+ me = me.username()
+
+ for term in psutil.users():
+ terminfo = {
+ k:v for k,v in term.__dict__.iteritems() if v and k not in ('host', 'name')
+ }
+
+ if 'terminal' in terminfo:
+ try:
+ terminfo['idle'] = int(time.time()) - int(os.stat(
+ '/dev/{}'.format(terminfo['terminal'])
+ ).st_atime)
+ except Exception, e:
+ pass
+
+ if terminfo['terminal'] in terminals:
+ terminfo.update(terminals[terminfo['terminal']])
+
+ host = term.host or '-'
+
+ if not term.name in info:
+ info[term.name] = {}
+
+ if not host in info[term.name]:
+ info[term.name][host] = []
+
+ if term.name == me or me.endswith('\\'+term.name):
+ terminfo['me'] = True
+
+ info[term.name][host].append(terminfo)
+
+ return info
+
+def connections():
+ info = {}
+ me = psutil.Process()
+
+
if __name__ == '__main__':
- print pstree()
+ print users()