tuerd: Get peer information from socket
[saartuer.git] / tyshell
1 #!/usr/bin/python3
2 import os
3 import readline
4 import shlex
5 import sys
6 import subprocess
7 import socket
8
9 tuerSock = "/run/tuer.sock"
10
11 # use a histfile
12 # FIXME: Why not ".tyshellhist"?
13 histfile = os.path.join(os.path.expanduser("~"), ".pyshellhist")
14 try:
15     readline.read_history_file(histfile)
16 except IOError:
17     pass
18 import atexit
19 atexit.register(readline.write_history_file, histfile)
20 atexit.register(print, "Bye")
21
22 # available commands
23 def help(c):
24         print("Available commands: %s" % ", ".join(sorted(commands.keys())))
25
26 def extcmd(cmd):
27         def run(c):
28                 ret = subprocess.call(cmd)
29                 if ret != 0:
30                         print("Command returned non-zero exit statis %d" % ret)
31         return run
32
33 def sendcmd(addr, cmd):
34         def run(c):
35                 print("Running %s..." % (cmd))
36                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
37                 s.connect(addr)
38                 s.send(cmd.encode())
39                 data = s.recv(4)
40                 s.close()
41                 print("...done")
42                 if data != b'1':
43                         print("Received unexpected answer %s" % str(data))
44         return run
45
46 def exitcmd(c):
47         sys.exit(0)
48
49 commands = {
50         'exit': exitcmd,
51         'help': help,
52         'open': sendcmd(tuerSock, 'open'),
53         'close': sendcmd(tuerSock, 'close'),
54         'buzz': sendcmd(tuerSock, 'buzz'),
55 }
56
57 # input loop
58 print("Welcome to tyshell. Use help to see what you can do.")
59 while True:
60         try:
61                 command = input("$ ")
62         except EOFError:
63                 print()
64                 break
65         command = shlex.split(command)
66         if not len(command): continue
67         # execute command
68         if command[0] in commands:
69                 try:
70                         commands[command[0]](command)
71                 except Exception as e:
72                         print("Error while executing %s: %s" % (command[0], str(e)))
73         else:
74                 print("Command %s not found. Use help." % command[0])
75