-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
56 lines (45 loc) · 1.92 KB
/
server.py
File metadata and controls
56 lines (45 loc) · 1.92 KB
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
#!/usr/bin/env python
# WS server that run command from server
# send command like this from server:
# ifconfig
# df
# "for i in {1..3}; do sleep 1 && echo \"current time: `date`\"; done"
import asyncio
import datetime
import random
import websockets
import subprocess
async def run_cmd(websocket, path):
async for message in websocket:
print(f"> {message} {path}")
greeting = f"> {message}"
await websocket.send(greeting)
if message:
print ('Recieved from ' + str(websocket.remote_address) + ': ' + message)
# For Linux, use '/bin/sh ', for windows: cmd.exe /c
# "universal newline support" :
# This will cause to interpret \n, \r\n and \r equally, each as a newline String (not bytes).
proc = subprocess.Popen('/bin/sh -c ' + message, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE,
bufsize=1, universal_newlines=True)
for line in proc.stdout:
line = line.rstrip()
print(f"line = {line}")
await websocket.send(line) #line.decode('utf-8') if universal_newlines not specified
# if the process has completed:
print("command done!")
await websocket.send("done!")
else:
await websocket.send('Non unicode data received! Send text please :)')
# asyncio.get_event_loop().run_until_complete(websockets.serve(run_cmd, 'localhost', 5678))
# asyncio.get_event_loop().run_forever()
def start_server_main_in_sync():
# start websocket server
start_server = websockets.serve(run_cmd, 'localhost', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
async def main():
async with websockets.serve(run_cmd, "localhost", 5678):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())