Пример #1
0
 def addUTMPEntry(self, loggedIn=1):
     if not utmp:
         return
     ipAddress = self.avatar.conn.transport.transport.getPeer().host
     (packedIp, ) = struct.unpack("L", socket.inet_aton(ipAddress))
     ttyName = self.ptyTuple[2][5:]
     t = time.time()
     t1 = int(t)
     t2 = int((t - t1) * 1e6)
     entry = utmp.UtmpEntry()
     entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
     entry.ut_pid = self.pty.pid
     entry.ut_line = ttyName
     entry.ut_id = ttyName[-4:]
     entry.ut_tv = (t1, t2)
     if loggedIn:
         entry.ut_user = self.avatar.username
         entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
         entry.ut_addr_v6 = (packedIp, 0, 0, 0)
     a = utmp.UtmpRecord(utmp.UTMP_FILE)
     a.pututline(entry)
     a.endutent()
     b = utmp.UtmpRecord(utmp.WTMP_FILE)
     b.pututline(entry)
     b.endutent()
Пример #2
0
 def ls():
     """return the list of users on the machine."""
     f = UTMPCONST.USER_PROCESS  # filter for
     u = utmp.UtmpRecord()  # iterator
     users = [x.ut_user for x in u if x.ut_type == f]
     u.endutent()  # close the utmp file!
     return users
Пример #3
0
def utmp_count():
    u = utmp.UtmpRecord()
    users = 0
    for i in u:
        if i.ut_type == utmp.USER_PROCESS:
            users += 1
    return users
Пример #4
0
def read_func():
    total = 0
    domain_counter = {}
    for d in domains:
        domain_counter[d] = 0
    records = utmp.UtmpRecord()
    for rec in records:
        if rec.ut_type == USER_PROCESS:
            (rec.ut_user, rec.ut_line, rec.ut_pid, rec.ut_host,
             time.ctime(rec.ut_tv[0]))
            host = rec.ut_host
            for d in domains:
                collectd.debug("HERE: %s %s" % (host, d))
                if d in host and host.endswith(d) == True:
                    collectd.debug('Matches')
                    domain_counter[d] = domain_counter[d] + 1
            total = total + 1
    records.endutent()
    datapoint = collectd.Values(plugin='sessions', )
    datapoint.type = 'count'
    datapoint.type_instance = 'total_sessions'
    datapoint.values = [total]
    collectd.debug('Dispatching a value of %s for total sessions' % total)
    datapoint.dispatch()

    for d in domains:
        datapoint = collectd.Values(plugin='sessions', )
        datapoint.type = 'count'
        datapoint.type_instance = d
        datapoint.values = [domain_counter[d]]
        collectd.debug('Dispatching a value of %s for domain sessions %s' %
                       (domain_counter[d], d))
        datapoint.dispatch()
Пример #5
0
    def extract(self):
        for name in self.vars: self.val[name] = 0
        for u in utmp.UtmpRecord():
#           print('# type:%s pid:%s line:%s id:%s user:%s host:%s session:%s' % (i.ut_type, i.ut_pid, i.ut_line, i.ut_id, i.ut_user, i.ut_host, i.ut_session))
            if u.ut_type == utmp.USER_PROCESS:
                self.val['users'] = self.val['users'] + 1
                if u.ut_user == 'root':
                    self.val['root'] = self.val['root'] + 1
            self.val['sessions'] = self.val['sessions'] + 1
Пример #6
0
def _idle(update_ttys=False):
    """returns the min idle time of the current user. you can optionally
	update the idle times of the other tty's to prevent any sudden jumps
	in values from this function, should a recent terminal be closed."""

    idle = None
    user = getpass.getuser()
    u = utmp.UtmpRecord()  # iterator
    tty = {}  # dictionary of stats
    for x in u:
        if x.ut_type == UTMPCONST.USER_PROCESS \
        and x.ut_user == user:
            # try/except in case /dev/* doesn't work/exist
            try:
                tty[x.ut_line] = os.stat('/dev/' + x.ut_line)
                z = time.time() - tty[x.ut_line][stat.ST_ATIME]
            except:
                z = None

            if z is not None:
                if idle is None: idle = z
                idle = min(idle, z)
    # possible values from utmp, and formatting data:
    # '%-10s %-5s %10s %-10s %-25s %-15s %-10s %-10s %-10s %-10s %-10s'
    # (USER, TTY, PID, HOST, LOGIN, IDLE, TYPE, SESSION, ID, EXIT, IPV6')
    # (x.ut_user, x.ut_line, x.ut_pid, x.ut_host, time.ctime(x.ut_tv[0]),
    # z, x.ut_type, x.ut_session, x.ut_id, x.ut_exit, x.ut_addr_v6)

    u.endutent()  # close the utmp file!

    # if you `watch' the output of this function, the idle time value will
    # slowly increase as the time passes. if you then close the least idle
    # terminal, suddenly the idle time will jump to that of the next least
    # idle. the bad side effect is that a system which is being used alot,
    # can suddenly seem as if it's been idle for a very long time. to stop
    # this from happening, we can optionally `touch' all the /dev/'s using
    # python os.utime and change them to match the least idle tty. if this
    # is what you want, then you must choose so explicitly, and accept all
    # of the consequences. (whatever they may be!) only ATIME is modified.
    if update_ttys:
        if idle is None: add = 0
        else: add = idle
        for (key, value) in tty.items():
            # set the ATIME to now + however long the shortest /dev/ has
            # been idle for. this is similar to using unix `touch, minus
            # the extra idle offset we add on so as not to reset it all.
            try:
                os.utime('/dev/' + key,
                         (time.time() + add, value[stat.ST_MTIME]))
            except OSError, e:
                if e.errno == errno.EPERM:
                    pass
                else:
                    raise e
Пример #7
0
def load_wtmp_file():
    """Parse wtmp file and extract login data
    """
    logins = []
    wf = utmp.UtmpRecord(UTMPCONST.WTMP_FILE)
    while True:
        user = wf.getutent()
        if not user:
            break

        if user[0] == UTMPCONST.USER_PROCESS:
            logins.append(
                (user.ut_tv[0], user.ut_user, user.ut_host, user.ut_addr_v6))

    wf.endutent()
    return sorted(logins)
Пример #8
0
def lastlogin(u, user):
    lastlogin = 0
    u.setutent()
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b['ut_type'] in (USER_PROCESS, DEAD_PROCESS) and \
           b['ut_user'] == user and \
           b['ut_tv'][0]>lastlogin:
            lastlogin = b['ut_tv'][0]

    u = utmp.UtmpRecord(WTMP_FILE)
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b['ut_type'] in (USER_PROCESS, DEAD_PROCESS) and \
           b['ut_user'] == user and \
           b['ut_tv'][0]>lastlogin:
            lastlogin = b['ut_tv'][0]
    u.endutent()
    return lastlogin
Пример #9
0
def lastlogin(u, user):
    lastlogin = 0, ""
    u.setutent()
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b.ut_type in (USER_PROCESS, DEAD_PROCESS) and \
           b.ut_user == user and \
           b.ut_tv[0]>lastlogin[0]:
            lastlogin = b.ut_tv[0], b.ut_host

    u = utmp.UtmpRecord(WTMP_FILE)
    while 1:
        b = u.getutent_dict()
        if not b:
            break
        if b.ut_type in (USER_PROCESS, DEAD_PROCESS) and \
           b.ut_user == user and \
           b.ut_tv[0]>lastlogin[0]:
            lastlogin = b.ut_tv[0], b.ut_host
    u.endutent()
    return lastlogin
Пример #10
0
if meminfo['SwapTotal:'] == 0: swapperc = '---'

print("  System information as of %s\n" % time.asctime())
print("  System load:  %-5.2f                Processes:           %d" %
      (loadav, processes))
print("  Memory usage: %-4s                 Users logged in:     %d" %
      (memperc, users))
print("  Swap usage:   %s" % (swapperc))

print("  Disk Usage:")
for k in sorted(statfs.keys()):
    print("    Usage of %-24s: %-20s" % (k, statfs[k]))

print("  Inode Usage:")
for l in sorted(iStatfs.keys()):
    print("    Usage of %-24s: %-20s" % (l, iStatfs[l]))

if users > 0:
    a = utmp.UtmpRecord()

    print("\n  Logged in users:")

    for b in a:  # example of using an iterator
        if b.ut_type == USER_PROCESS:
            print("  \033[1;31m%-10s\033[m from %-25s at %-20s" % \
            (b.ut_user, b.ut_host, time.ctime(b.ut_tv[0])))
    a.endutent()

sys.exit(0)
Пример #11
0
#!/usr/bin/python
# poor man's last

import utmp
from UTMPCONST import *
import time

a = utmp.UtmpRecord(WTMP_FILE)

print "%-10s %-10s %-30s %-20s" % ("USER", "TTY", "HOST", "LOGIN")

while 1:
    b = a.getutent()
    if not b:
        break
    if b[0] == USER_PROCESS:
        print "%-10s %-10s %-30s %-20s" % (b[4], b[2], b[5], time.ctime(
            b[8][0]))
a.endutent()
Пример #12
0
#!/usr/bin/python
'''
chkutmp.py 

checks /var/run/utmp for entries that have no corresponding entry in 
/proc/<PID>; such entries indicate some level of corruption in UTMP, 
which causes various problems for some applications

TODO: 
 * handle sys.argv[1] passing of which file to process, 
 * cli switch to specify utmp or wtmp (or both)
'''
import utmp, time, os.path
from UTMPCONST import *

utmpRecord = utmp.UtmpRecord( UTMP_FILE )

headerNotSet = 1

while 1:
	utEntry = utmpRecord.getutent()
	if not utEntry:
		break
	if utEntry[0] == USER_PROCESS and not os.path.exists( ('/proc/%s' % utEntry[1]) ):
		if headerNotSet:
			print "%-10s %-10s %-30s %-27s %-8s %-5s" % ( "USER", "TTY", "HOST", "LOGIN", "PID", "STATUS" )
			headerNotSet = 0
		print "%-10s %-10s %-30s %-27s %-8d %-5d" % ( utEntry[4], utEntry[2], utEntry[5], time.ctime( utEntry[8][0] ), utEntry[1], -1 )

if headerNotSet:
	print UTMP_FILE, "appears to be in tact."
Пример #13
0
LINE_LIST = ['pts/0', 'pts/1', 'pts/2', 'pts/3', 'pts/4', 'pts/5']
TTY_LIST = ['ts/0', 'ts/1', 'ts/2', 'ts/3', 'ts/4', 'ts/5']
IP_FILE = 'addresses.txt'
USER_FILE = 'usernames.txt'
BOGUS_USER = "******"
BOGUS_IPS = ['76.192.3.2', '217.77.163.138']
BOGUS_ENTRY_INDEX = 1580
NR_ENTRIES = 2000
TIME_RANDOM_INTERVAL = 200
USER_PROCESS = 7

MAX_RED_HERRINGS = 3
SAFE_RED_HERRING_INTERVAL = 100800  # enough time to travel to another country

open(FILENAME, "w").close()  # truncate the file :/
NEW_RECORD = utmp.UtmpRecord(FILENAME)

# T0
timestamp = 1470587713

time_window = 128835
bad_ip = 0
users = []
ips = []

geoip = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
country_per_user = {}
last_seen = {}  # keyed by user
red_herrings = 0

#!/usr/bin/python
# python utmp doesn't work on all releases
import utmp
from UTMPCONST import USER_PROCESS
# "touch"
file('/tmp/utmp.bogus', 'w').close()
# add record...
a = utmp.UtmpRecord('/tmp/utmp.bogus')
b = utmp.UtmpEntry()
b.ut_type = USER_PROCESS
b.ut_pid = 10000
b.ut_user = "******"
b.ut_line = '/tmp/evil'
b.ut_host = 'localhost'
b.ut_tv = (0, 0)
a.pututline(b)