client.py:
#!/usr/bin/env python3
"""shell_client.py for python3. Read data from a socket and, read a command from stdin, and send the command over the socket."""
import socket
import time
import bufsock
# Give the server time to start up.
time.sleep(1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# We use port 4444 so we don't need to be root to run this.
s.connect(("127.0.0.1", 4444))
bs = bufsock.bufsock(s)
while True:
# Read the prompt and print it.
data = bs.readto(b'\n')
print(data)
# Read a command from the user's terminal.
cmd = input()
# Send the command to the server, terminated with a newline.
bs.send(cmd.encode('utf-8'))
bs.send(b'\n')
bs.flush()
# Read the command's always-one-line response and print it.
data = bs.readto(b'\n')
print(data)
server.py:
#!/usr/bin/env python3
"""Shell_server.py for python3. Accept a connection, read commands, execute them and send data back over the socket."""
import socket
import time
import bufsock
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# We use port 4444 so we don't need to be root to run this.
s.bind(("0.0.0.0", 4444))
s.listen(1)
while True:
connexion, client_address = s.accept()
print("connexion from: " + str(client_address))
bs = bufsock.bufsock(connexion)
while True:
bs.send(b"Entrer cmd:\n")
bs.flush()
cmd = bs.readto(b'\n').rstrip(b'\n')
if cmd == b'TIME':
result = time.ctime().encode('utf-8')
bs.send(result)
else:
bs.send(b'Unrecognized command: %s' % (cmd, ))
bs.send(b'\n')
bs.flush()
bufsock.py:
https://stromberg.dnsalias.org/~strombrg/bufsock.html
…and I’m realizing tonight, that I should put bufsock on pypi.