1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet import reactor
from twisted.internet.protocol import ServerFactory
from twisted.cred.credentials import UsernamePassword
class CommandProtocol(LineOnlyReceiver):
def connectionMade(self):
self.username = None
def hasPermission(self, command):
return command in self.factory.permissions[self.username]
def lineReceived(self, line):
arguments = line.split()
command = arguments.pop(0).upper()
method = getattr(self, 'command_' + command, None)
if method is None:
self.sendLine("Invalid command")
elif not self.hasPermission(command):
self.sendLine("Permission denied")
else:
self.sendLine(method(*arguments))
def command_AUTHENTICATE(self, username, password):
credentials = UsernamePassword(username, password)
validPassword = self.factory.credentials.get(username)
if credentials.checkPassword(validPassword):
self.username = username
return "Authenticated"
else:
return "Authentication failed"
def command_ADD(self, left, right):
return str(int(left) + int(right))
def command_MUL(self, left, right):
return str(int(left) * int(right))
def command_DIV(self, left, right):
return str(int(left) / int(right))
class CommandFactory(ServerFactory):
protocol = CommandProtocol
def __init__(self, permissions, credentials):
self.permissions = permissions
self.credentials = credentials
def main():
permissions = {
None: ['AUTHENTICATE', 'ADD', 'MUL'],
'alice': ['ADD', 'MUL', 'DIV']}
credentials = {'alice': 'password'}
factory = CommandFactory(permissions, credentials)
reactor.listenTCP(12345, factory)
reactor.run()
if __name__ == '__main__':
main()
|