]> gitweb.pimeys.fr Git - scripts-20-100.git/blob - whothefuckishere.py
typo
[scripts-20-100.git] / whothefuckishere.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3
4 """ Codé par 20-100
5
6 Pour savoir qui est connecté ici."""
7
8 import subprocess
9 import re
10 import socket
11
12 def execute(command, display_err=True):
13 """Exécute une commande et renvoie le résultat."""
14 proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
15 out, err = proc.communicate()
16 if err and display_err:
17 print err
18 else:
19 return out
20
21 def get_who():
22 """Exécute le who et récupère les utilisateurs distants."""
23 who_regex = re.compile("(?P<user>[^ ]+) +(?P<pts>[^ ]+) +(?P<date>[^ ]+) (?P<hour>[^ ]+) \((?P<from>[^ ]+)\)\n")
24 raw_who = execute(["who"])
25 who = [m.groupdict() for m in who_regex.finditer(raw_who)]
26 return raw_who, [w for w in who if not w["from"].startswith(":0")]
27
28 def get_netstat():
29 """Effectue le netstat et récupère les ports intéressants."""
30 netstat_regex = re.compile("tcp[^\n]+kfet.crans.org:ssh +(?P<host>[^ :]+):(?P<port>[0-9]+)")
31 # -t parce qu'on s'intéresse au TCP
32 # -p c'est pour avoir le PID, mais en fait comme les process sshd appartiennent à root, on n'a rien
33 # -W permet d'avoir l'hostname en entier
34 raw_netstat = execute(["netstat", "-t", "-p", "-W"], display_err=False)
35 netstat = [m.groupdict() for m in netstat_regex.finditer(raw_netstat)]
36 return raw_netstat, netstat
37
38 def ask_idents(ports_couples, host):
39 """Va demander les usernames."""
40 question = "\n".join(["%s, %s" % (p1, p2) for (p1, p2) in ports_couples]) + "\n"
41 s=socket.socket()
42 try:
43 s.connect((host, 113))
44 except socket.error as e:
45 return "%s : %s" % e.args
46 s.send(question)
47 answer = s.recv(100000)
48 return answer
49
50 def do_all():
51 # On exécute un who
52 raw_who, who = get_who()
53 print "Résultat du who :"
54 print raw_who
55 raw_netstat, netstat = get_netstat()
56 hosts = list(set([ns["host"] for ns in netstat]))
57 ns = {h : ask_idents([(ns["port"], 22) for ns in netstat if ns["host"] == h], h) for h in hosts}
58 print "Ce que nous apprend netstat :"
59 for (host, people) in ns.iteritems():
60 print " en provenance de %s:" % (host,)
61 print " " + " ".join(people.split("\n"))
62
63
64 if __name__ == "__main__":
65 do_all()