Created
April 1, 2013 19:46
-
-
Save zachwalton/5287198 to your computer and use it in GitHub Desktop.
a method and a class for interacting over a socket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Listener(object): | |
""" | |
This accepts a list of `commands` and associated `responses` and opens a | |
socket on `port`. It then listens for any of the commands and dumps | |
the associated response. | |
Example: | |
Listener.listen(port=57359, | |
commands = [ "give_me_your_name", | |
"give_me_your_slogan" ], | |
responses = [ "nationwide", | |
"on your side!" ]) | |
Connecting to port 57359 from another host and issuing "give_me_your_name" | |
would then send "nationwide" in response, and issuing "give_me_your_slogan" | |
would respond with "on your side!". | |
This could be used for passing around config files without going through | |
SSH, etc. | |
Returns the name of the host that connected. | |
See connect() for the sister method. | |
""" | |
def __init__(self): | |
self.s_listen = None | |
def listen(self, commands, responses, port=57359): | |
HOST = '' | |
PORT = port | |
if not self.s_listen: | |
self.s_listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.s_listen.bind((HOST, PORT)) | |
self.s_listen.listen(1) | |
conn, addr = self.s_listen.accept() | |
host = socket.gethostbyaddr(addr[0]) | |
while 1: | |
data = conn.recv(1024) | |
for command in commands: | |
try: | |
data.index(command) | |
conn.sendall(responses[commands.index(command)]) | |
conn.close() | |
return host[0] | |
except ValueError: pass | |
def connect(node, command, port=57359): | |
""" | |
Connects to `node` on `port` and issues `command`. Assumes that `node` | |
is already listening on the provided port and knows how to respond to | |
`command`. | |
Raises exception if a connection cannot be established, else returns the | |
response issued by the host in response to `command`. | |
See Listener() for the sister class. | |
""" | |
HOST = node | |
PORT = port | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
try: | |
s.connect((HOST,PORT)) | |
except: | |
s.close() | |
raise | |
s.sendall(command) | |
response = "" | |
while 1: | |
data = s.recv(1024) | |
if not data: break | |
response += data | |
s.close() | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment