10 from collections import namedtuple
12 tuerSock = "/run/tuer.sock"
15 histfile = os.path.join(os.path.expanduser("~"), ".tyshellhist")
17 readline.read_history_file(histfile)
21 atexit.register(readline.write_history_file, histfile)
26 print(commands.get(c[1],(None,'Can\'t find help for command %s'%(c[1]))).helpstring)
28 print("Available commands: %s" % ", ".join(sorted(commands.keys())))
29 print("Use 'help command' to get more information on the command 'command'")
33 ret = subprocess.call(cmd)
35 print("Command returned non-zero exit statis %d" % ret)
38 def sendcmd(addr, cmd):
40 print("206 Sending command %s..." % (cmd))
41 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
47 print(data.decode('utf-8'))
55 for n in grp.getgrnam("tuer").gr_mem:
57 print (p.pw_name, " - ", p.pw_gecos)
59 def alias (cmds, aliases):
60 for newname, oldname in aliases.items():
61 cmds[newname] = cmds[oldname]
64 CmdEntry = namedtuple('CmdEntry','function helpstring')
67 'exit': CmdEntry(exitcmd, 'Quits this shell'),
68 'help': CmdEntry(helpcmd, 'Helps you getting to know the available commands'),
69 'unlock': CmdEntry(sendcmd(tuerSock, 'unlock'), 'Will try to unlock the apartment door'),
70 'buzz': CmdEntry(sendcmd(tuerSock, 'buzz'), 'Will buzz the buzzer for the street door'),
71 'who': CmdEntry(whocmd, 'Shows the list of people, who are allowed to control this system'),
77 def complete_command(cmd):
78 '''returns a list of commands (as strings) starting with cmd'''
79 return list(filter(lambda x: x.startswith(cmd), commands.keys()))
80 readline.set_completer(lambda cmd, num: (complete_command(cmd)+[None])[num]) # wrap complete_command for readline's weird completer API
81 readline.parse_and_bind("tab: complete") # run completion on tab
84 print("Welcome to tyshell. Use help to see what you can do.")
91 command = shlex.split(command)
92 if not len(command): continue
93 # find suiting commands
94 if command[0] in commands: # needed in case a complete command is a prefix of another one
95 cmdoptions = [command[0]]
97 cmdoptions = complete_command(command[0])
98 # check how many we found
99 if len(cmdoptions) == 0: # no commands fit prefix
100 print("Command %s not found. Use help." % command[0])
101 elif len(cmdoptions) == 1: # exactly one command fits (prefix)
103 res = commands[cmdoptions[0]].function(command)
105 except Exception as e:
106 print("Error while executing %s: %s" % (command[0], str(e)))
107 else: # multiple commands fit the prefix
108 print("Ambiguous command prefix, please choose one of the following:")
109 print("\t", " ".join(cmdoptions))
110 # TODO: put current "command[0]" into the shell for the next command, but such that it is deletable with backspace