Skip to content

Instantly share code, notes, and snippets.

@kstoneriv3
Created July 12, 2025 22:23
Show Gist options
  • Save kstoneriv3/a8c919e402a2ac01a860f234654b1d03 to your computer and use it in GitHub Desktop.
Save kstoneriv3/a8c919e402a2ac01a860f234654b1d03 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import subprocess
import os
import sys
def launch():
# Ensure python binary and script path are correct
cmd = [sys.executable, 'telnet_shell.py']
# start_new_session=True → child is in a new session group
# stdout/stderr can go to log files or /dev/null
with open('telnet_shell.log', 'ab', 0) as logf:
subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,
stdout=logf,
stderr=logf,
start_new_session=True
)
print("Launched telnet_shell.py in background.")
if __name__ == '__main__':
launch()
import socket
import threading
import os
import pty
import select
import signal # ← for sending SIGKILL
import time
def handle_client(conn):
# Fork a new process with a PTY
pid, fd = pty.fork()
if pid == 0:
# Child process: replace with bash
os.execv("/bin/bash", ["/bin/bash"])
else:
# Parent process: schedule a kill after 15 minutes
def kill_shell():
try:
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass # already exited
timer = threading.Timer(900, kill_shell)
timer.daemon = True
timer.start()
# Relay data between socket and PTY master
try:
while True:
rlist, _, _ = select.select([conn, fd], [], [])
if conn in rlist:
data = conn.recv(1024)
if not data:
break
os.write(fd, data)
if fd in rlist:
output = os.read(fd, 1024)
if not output:
break
conn.sendall(output)
finally:
conn.close()
timer.cancel() # in case the shell exited early
def main():
host = "0.0.0.0"
port = 2323 # unprivileged port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen(5)
print(f"[*] Listening on {host}:{port}")
try:
while True:
conn, addr = server.accept()
print(f"[*] Connection from {addr}, shell will auto-kill in 15 min")
t = threading.Thread(target=handle_client, args=(conn,))
t.daemon = True
t.start()
except KeyboardInterrupt:
print("\n[*] Shutting down.")
finally:
server.close()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment