From: Vincent Le Gallic Date: Tue, 23 Sep 2014 00:51:45 +0000 (+0200) Subject: Script pour stalker les gens connectés X-Git-Url: http://gitweb.pimeys.fr/?p=scripts-20-100.git;a=commitdiff_plain;h=418eed66d766d4d2fb2471bc212767a7ec8a78b3 Script pour stalker les gens connectés --- diff --git a/whothefuckishere.py b/whothefuckishere.py new file mode 100755 index 0000000..a3e667b --- /dev/null +++ b/whothefuckishere.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python +# -*- encoding: utf-8 -*- + +""" Codé par 20-100 + + Pour savoir qui est connecté ici.""" + +import subprocess +import re +import socket + +def execute(command, display_err=True): + """Exécute une commande et renvoie le résultat.""" + proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = proc.communicate() + if err and display_err: + print err + else: + return out + +def get_who(): + """Exécute le who et récupère les utilisateurs distants.""" + who_regex = re.compile("(?P[^ ]+) +(?P[^ ]+) +(?P[^ ]+) (?P[^ ]+) \((?P[^ ]+)\)\n") + raw_who = execute(["who"]) + who = [m.groupdict() for m in who_regex.finditer(raw_who)] + return raw_who, [w for w in who if not w["from"].startswith(":0")] + +def get_netstat(): + """Effectue le netstat et récupère les ports intéressants.""" + netstat_regex = re.compile("tcp[^\n]+kfet.crans.org:ssh +(?P[^ :]+):(?P[0-9]+)") + # -t parce qu'on s'intéresse au TCP + # -p c'est pour avoir le PID, mais en fait comme les process sshd appartiennent à root, on n'a rien + # -W permet d'avoir l'hostname en entier + raw_netstat = execute(["netstat", "-t", "-p", "-W"], display_err=False) + netstat = [m.groupdict() for m in netstat_regex.finditer(raw_netstat)] + return raw_netstat, netstat + +def ask_idents(ports_couples, host): + """Va demander les usernames.""" + question = "\n".join(["%s, %s" % (p1, p2) for (p1, p2) in ports_couples]) + "\n" + s=socket.socket() + try: + s.connect((host, 113)) + except socket.error as e: + return "%s : %s" % e.args + s.send(question) + answer = s.recv(100000) + return answer + +def do_all(): + # On exécute un who + raw_who, who = get_who() + print "Résultat du who :" + print raw_who + raw_netstat, netstat = get_netstat() + hosts = list(set([ns["host"] for ns in netstat])) + ns = {h : ask_idents([(ns["port"], 22) for ns in netstat if ns["host"] == h], h) for h in hosts} + print "Ce que nous apprend netstat :" + for (host, people) in ns.iteritems(): + print " en provenance de %s:" % (host,) + print " " + " ".join(people.split("\n")) + + +if __name__ == "__main__": + do_all()