motd: rewrite sysctl_get function for better python 3 support
[freebsd-maintainer-scripts/.git] / motd.py
1 import os
2 import shlex
3 import subprocess
4
5
6 template = r"""%s
7  +--------------------------------------+           ,        ,
8  |        Welcome to %s           |          /(        )`
9  |                                      |          \ \___   / |
10  |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~|          /- _  `-/  '
11  |                                      |         (/\/ \ \   /\
12  |  kern.hostname: %.8s               |         / /   | `    \
13  |    kern.ostype: %s              |         O O   ) /    |
14  | kern.osrelease: %s          |         `-^--'`<     '
15  |       hw.model: %.20s |        (_.)  _  )   /
16  |     hw.machine: %s                |         `.___/`    /
17  |        hw.ncpu: %s                    |           `-----' /
18  | dev.cpu.0.freq: %s                <----.     __ / __   \
19  |     hw.physmem: %s         <----|====O)))==) \) /====
20  |           inet: %s        <----'    `--' `.__,' \
21  |                                      |           |        |
22  |          admin: %s         |            \       /
23  |                                      |       ______( (_  / \______
24  |                                      |     ,'  ,-----'   |        \
25  +--------------------------------------+     `--{__________)        \/
26 """
27
28
29 def run_command(cmd: str) -> str:
30     p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
31     try:
32         out, err = p.communicate(timeout=10)
33
34     except subprocess.TimeoutExpired:
35         p.kill()
36         out, _ = p.communicate()
37
38     return out.strip()
39
40
41 def sysctl_get(oid_string: str) -> str:
42     result = ""
43     try:
44         import freebsd
45         result = freebsd.sysctl('%s' % oid_string)
46     except ImportError:
47         cmd = 'sysctl -n {0}'.format(oid_string)
48         result = run_command(cmd)
49     finally:
50         return str(result, 'utf-8')
51
52
53 uname = " ".join(" ".join(os.uname()[:4]).split(' ')[:13])
54 fqdn = "6dev.net"
55 admin = "%s@%s" % (os.environ['USER'], fqdn)
56 inet = os.popen("ifconfig|grep 'inet .* broad*'").read().split()[1]
57
58 oids = ["kern.hostname", "kern.osrelease", "kern.ostype", "hw.model",
59         "hw.machine", "hw.ncpu", "dev.cpu.0.freq", "hw.physmem"]
60
61 for oid in oids:
62     locals()[oid.replace('.', '_')] = sysctl_get(oid)
63
64 hw_physmem = "%.1fGB" % float(int(hw_physmem)/1000000000.0)
65
66 print(template % (uname, fqdn,
67                   kern_hostname.split('.')[0], kern_ostype, kern_osrelease,
68                   hw_model, hw_machine, hw_ncpu,
69                   dev_cpu_0_freq, hw_physmem, inet, admin))