Thx for guidance/help!
I need to log a Telnet session that could last up to 5 hours.
Each received line needs a time stamp (the received data will not have a time stamp so I need to inject this)
I tried Putty and MobaXterm but they do not timestamp the lines. This is a requirement to troubleshoot the problem with the device.
I’m FAR from a Linux expert but there is a lot of info so I tried a few things.
Methods tried and failed…
-
use configuration.yaml
shell_command:
start_tcp_logger: nohup python3 /config/tcp_logger.py &
stop_tcp_logger: pkill -f tcp_logger.py -
Launch .py script rom Advanced SSH & Web Terminal
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import telnetlib
from datetime import datetime
import time
# ===== CONFIGURATION =====
HOST = "192.168.1.75" # Your TCP/Telnet device IP
PORT = 23 # Telnet port
LOGFILE = "/config/session_log.txt" # Output log file
RECONNECT_DELAY = 5 # Seconds to wait before retrying if disconnected
# =========================
while True:
try:
tn = telnetlib.Telnet(HOST, PORT)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Connected to {HOST}:{PORT}")
while True:
line = tn.read_until(b"\n")
if not line:
break
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
decoded_line = line.decode(errors="replace")
# Write to log file
with open(LOGFILE, "a") as f:
f.write(f"{timestamp} {decoded_line}")
# Print to terminal for live monitoring
print(f"{timestamp} {decoded_line}", end="")
except Exception as e:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Disconnected, retrying in {RECONNECT_DELAY}s...")
time.sleep(RECONNECT_DELAY)