Add w command

This commit is contained in:
Oleksii Shevchuk 2017-03-16 17:51:08 +02:00
parent 3db9dcd9ec
commit 991936ff3e
2 changed files with 119 additions and 1 deletions

67
pupy/modules/w.py Normal file
View File

@ -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)

View File

@ -4,6 +4,8 @@ import psutil
import collections import collections
import sys import sys
import os
import time
def pstree(): def pstree():
data = {} data = {}
@ -51,5 +53,54 @@ def pstree():
return min(tree), tree, data 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__': if __name__ == '__main__':
print pstree() print users()