-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelnet_client.py
More file actions
97 lines (81 loc) · 2.72 KB
/
Copy pathtelnet_client.py
File metadata and controls
97 lines (81 loc) · 2.72 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
94
95
96
97
"""
Simple telnet client implementation using sockets.
Replacement for deprecated telnetlib module.
"""
import socket
import threading
from typing import Optional
class TelnetClient:
"""Simple synchronous telnet client using raw sockets."""
def __init__(self, host: str, port: int, timeout: float = 5.0):
"""
Initialize telnet client.
Args:
host: Hostname or IP address
port: Port number
timeout: Connection timeout in seconds
"""
self.host = host
self.port = port
self.timeout = timeout
self.socket: Optional[socket.socket] = None
self.lock = threading.Lock()
def open(self) -> None:
"""Open connection to remote host."""
with self.lock:
if self.socket:
self.close()
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(self.timeout)
self.socket.connect((self.host, self.port))
def close(self) -> None:
"""Close the connection."""
with self.lock:
if self.socket:
try:
self.socket.close()
except Exception:
pass
finally:
self.socket = None
def write(self, data: bytes) -> None:
"""
Write data to the socket.
Args:
data: Bytes to send
Raises:
ConnectionError: If not connected or send fails
"""
with self.lock:
if not self.socket:
raise ConnectionError("Not connected")
self.socket.sendall(data)
def read_until(self, delimiter: bytes, timeout: Optional[float] = None) -> bytes:
"""
Read data until delimiter is found.
Args:
delimiter: Byte sequence to read until
timeout: Optional timeout override
Returns:
Bytes read including delimiter
Raises:
ConnectionError: If not connected
socket.timeout: If timeout occurs
"""
with self.lock:
if not self.socket:
raise ConnectionError("Not connected")
original_timeout = self.socket.gettimeout()
if timeout is not None:
self.socket.settimeout(timeout)
try:
buffer = b''
while delimiter not in buffer:
chunk = self.socket.recv(1024)
if not chunk:
break
buffer += chunk
return buffer
finally:
if timeout is not None:
self.socket.settimeout(original_timeout)