server.py 4.13 KB
Newer Older
1 2 3 4 5
"""
Permet d'avoir quelques informations sur le système:
- le type d'OS
- version de l'OS
- le nombre d'utilisateurs connectés
6
- la liste des utilisateurs connectés
7 8 9
"""
import argparse
import logging
10 11
import platform
import os
12 13
import sys
import subprocess
14
import socket
Sébastien's avatar
Sébastien committed
15
import psutil
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
LOG = logging.getLogger("osinfo")

class CustomFormatter(argparse.RawDescriptionHelpFormatter,
                      argparse.ArgumentDefaultsHelpFormatter):
    pass


def parse_args(args):
    """Parse arguments."""
    parser = argparse.ArgumentParser(
        description=sys.modules[__name__].__doc__,
        formatter_class=CustomFormatter)
    g = parser.add_mutually_exclusive_group()
    g.add_argument("--debug", "-d", action="store_true",
                   default=False,
                   help="enable debugging")
    g.add_argument("--silent", "-s", action="store_true",
                   default=False,
                   help="don't log to console")
    return parser.parse_args(args)

def setup_logging(options):
    """Configure logging."""
    root = logging.getLogger("osinfo")
    root.setLevel(logging.WARNING)
    LOG.setLevel(options.debug and logging.DEBUG or logging.INFO)
    if not options.silent:
Sébastien's avatar
Sébastien committed
44 45 46 47
        ch = logging.StreamHandler()
        ch.setFormatter(logging.Formatter(
            "%(levelname)s[%(name)s] %(message)s"))
        root.addHandler(ch)
48

Bonnegent's avatar
Bonnegent committed
49
def main(host="0.0.0.0", port=7777):
50 51 52 53
    """Va retourner les informations suivantes sur une même ligne,
    en utilisant un ';' comme séparateur.

    Exemple:
54
    os;os_version;nb_users
55 56 57 58 59
    """
    mySocket = socket.socket()
    mySocket.bind((host,port))

    mySocket.listen(1)
Sébastien's avatar
Sébastien committed
60
    while True:
61
        conn, addr = mySocket.accept()
62
        LOG.debug("connection from: " + str(addr))
63
        data = conn.recv(1024).decode()
64
        LOG.debug("received from client: " + str(data))
65 66
        system = platform.system()
        if system == 'Linux':
67 68
            out = subprocess.run(["/usr/bin/lsb_release", "-ds"], stdout=subprocess.PIPE)
            os_name = out.stdout.decode().replace('\n', '')
69
            os_version = get_os_version()
Sébastien's avatar
Sébastien committed
70
            # os_users = get_users_linux()
71 72 73
        elif system == 'Windows':
            # Windows 10
            os_name = "%s %s" % (system, platform.release())
74
            os_version = platform.version()
Sébastien's avatar
Sébastien committed
75
            # os_users = get_users_windows()
76

77 78 79 80
        os_users_count = len(psutil.users())
        tmp = []
        for user in psutil.users():
            timestamp = int(user.started)
81
            tmp.append(f"{user.name}:{timestamp}")
82
        os_users = ",".join(tmp)
Sébastien's avatar
Sébastien committed
83
        # message = "%s;%s;%s" % (os_name, os_version, os_users)
84
        message = f"{os_name};{os_version};{os_users_count};{os_users}"
85

Sébastien's avatar
Sébastien committed
86
        LOG.debug(f"sending: {message}")
87 88 89 90 91 92 93 94 95 96
        conn.send(message.encode())
    conn.close()

def get_os_version():
    "Cas des postes pédago"
    file_version = "/etc/version"
    try:
        fd = open(file_version, 'r')
        tmp = fd.readline().split('\n')[0]
    except Exception:
97
        version = '?'
98 99 100 101 102 103 104 105
    else:
        version = tmp
    return version

def get_load():
    try:
        load = os.getloadavg()[1]
    except Exception:
106
        load = "?"
107 108
    return load

109 110 111 112 113 114 115 116 117 118 119 120 121 122
def get_users_linux():
    try:
        # seulement version > 3.7
        # out = subprocess.run(["users"], capture_output=True)
        out = subprocess.run(["users"], stdout=subprocess.PIPE)
        txt = out.stdout.decode().split()
        # txt: ['root'] ou ['root', 'root'] ou ['']
        nb = len(txt)
        if nb == 1 and txt[0] == '':
            users = "0"
        else:
            users = f"{nb}"
    except Exception:
        users = "?"
Sébastien's avatar
Sébastien committed
123
    LOG.debug(f"utilisateurs connectés: {users}")
124
    return users
125

126
def get_users_windows():
Sébastien's avatar
Sébastien committed
127
    try:
Sébastien's avatar
Sébastien committed
128
        out = subprocess.run(["c:\Windows\System32\quser.exe"], stdout=subprocess.PIPE)
Sébastien's avatar
Sébastien committed
129
        txt = out.stdout.decode()
Sébastien's avatar
Sébastien committed
130
        LOG.debug(txt)
Sébastien's avatar
Sébastien committed
131 132 133 134
        nb = txt.count("Actif")
        users = f"{nb}"
    except Exception:
        users = "?"
Sébastien's avatar
Sébastien committed
135
    LOG.debug(f"utilisateurs connectés: {users}")
Sébastien's avatar
Sébastien committed
136
    return users
137 138 139


if __name__ == "__main__":
140 141 142 143 144
    options = parse_args(sys.argv[1:])
    setup_logging(options)
    LOG.info("starting...")
    main()
    sys.exit()
145