-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_manager.py
More file actions
93 lines (71 loc) · 1.77 KB
/
Copy pathssh_manager.py
File metadata and controls
93 lines (71 loc) · 1.77 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import asyncio
import asyncssh
from db import save_session, delete_session, update_timestamp
from config import SESSION_TIMEOUT
active_sessions = {}
async def ssh_reader(uid):
sess = active_sessions.get(uid)
if not sess:
return
proc = sess["proc"]
queue = sess["queue"]
try:
while True:
line = await proc.stdout.readline()
if not line:
break
await queue.put(line)
except Exception:
pass
async def start_session(uid, ip, port, user, pw):
conn = await asyncssh.connect(
ip,
port=port,
username=user,
password=pw,
known_hosts=None
)
proc = await conn.create_process()
queue = asyncio.Queue()
active_sessions[uid] = {
"conn": conn,
"proc": proc,
"queue": queue,
"task": None
}
task = asyncio.create_task(ssh_reader(uid))
active_sessions[uid]["task"] = task
await save_session(uid, ip, port, user, pw)
async def close_session(uid):
sess = active_sessions.get(uid)
if not sess:
return
try:
sess["proc"].stdin.write("exit\n")
except:
pass
try:
sess["conn"].close()
except:
pass
try:
if sess["task"]:
sess["task"].cancel()
except:
pass
active_sessions.pop(uid, None)
await delete_session(uid)
async def send_command(uid, text):
sess = active_sessions.get(uid)
if not sess:
return None
sess["proc"].stdin.write(text + "\n")
await update_timestamp(uid)
output = ""
for _ in range(25):
try:
line = sess["queue"].get_nowait()
output += line
except asyncio.QueueEmpty:
break
return output or " "