Skip to content

Instantly share code, notes, and snippets.

@manpages
Created August 18, 2012 03:44
Show Gist options
  • Save manpages/3384203 to your computer and use it in GitHub Desktop.
Save manpages/3384203 to your computer and use it in GitHub Desktop.
Kerberos' telnet terminal
#!/usr/bin/python
#####################
# TelnetTerminal.py #
#===================#
# By Kerberos #
#####################
import os, sys, telnetlib, getopt, socket
from telnetlib import IAC, NOP
def Init():
CommandLoop()
return
def CommandLoop():
host = ""
port = -1
cwd = ""
user = ""
prompt = ""
cmd = ""
connected = False
session = None
while True:
if user <> "":
prompt = user + "@" + host + ":" + cwd + "# "
else:
prompt = "# "
sys.stdout.write(prompt)
# Read and processcommand
cmd = raw_input()
if len(cmd) == 0:
continue
args = cmd.split(" ")
if len(args) > 1:
args = args[1:]
if cmd.lower() in ("exit", "quit", "close", "off", "die"):
if connected:
session.close()
print "Disconnected from " + host
break
elif cmd.lower() == "help":
print "Commands: \n\texit, quit, close, off, die -> Exit the terminal"
print "\tconnect HOST [PORT] -> connect to HOST on PORT"
print "\tdisconnect -> disconnect from the host currently connect to"
print "\tget REMOTEFILE [LOCALFILE] -> downloads REMOTEFILE and save it to LOCALFILE"
print "\tput LOCALFILE REMOTEFILE -> uploads LOCALFILE to REMOTEFILE on the connected host"
print "\tfind REMOTEFILE -> searches the remote filesystem for the specified file"
print "\tstatus -> print the current connection status"
print "\t(Any valid host system command)"
elif cmd.lower()[:7] == "connect":
args = cmd[8:].split(" ")
if len(cmd) < 8:
print "Usage: connect HOST [PORT] [USER] PASS"
continue
# Parse args
host = args[0]
if len(args) == 2:
# Only host and pass specified
port = 23
user = "admin"
elif len(args) == 3:
try:
port = int(args[1])
except ValueError, err:
user = args[1]
if port == -1:
port = 23
elif user == "":
user = "admin"
elif len(args) == 4:
try:
port = int(args[1])
except ValueError, err:
print "[Error@Connect()] Invalid port number"
if port > 65535:
print "[Error@Connect()] Invalid port number"
continue
user = args[2]
else:
print "Usage: connect HOST [PORT] [USER] PASS"
continue
# Connect and attempt auth
try:
session = telnetlib.Telnet(host, port)
session.read_until("login:")
session.write(user + "\n")
session.read_until("Password:")
session.write(args[len(args) - 1] + "\n")
except socket.gaierror, err:
if "Servname not supported" in str(err):
print "[Error@Connect()] Invalid hostname specified"
else:
print "[Error@Connect()] " + str(err)
continue
# Verify login success
buff = ""
while True:
buff += session.read_some()
if "Login incorrect" in buff:
print "[Error@Connect()] Invalid credentials"
session.close()
break
elif buff[len(buff) - 2:] == "# ":
connected = True
break
if connected:
print ">> Successfully connected to " + host
# Attempt to read bound shell info
if "BusyBox" in buff:
buff = buff.strip()
print ">> Bound shell: " + buff[:buff.find("\n")]
# Get cwd
session.write("pwd\n")
session.read_until("\n")
resp = session.read_until("# ").replace("# ", "").strip()
if "/" in resp:
cwd = resp.strip()
elif "not found" in resp:
print ">> Server failed to run 'pwd' command, couldn't get cwd"
else:
print "[Error@Connect()] Failed to connect to " + host
elif cmd.lower() == "disconnect":
if connected:
connected = False
session.close()
print ">> Disconnected from " + host
else:
print ">> Not connected!"
elif cmd.lower()[:3] == "get":
if not connected:
print ">> Not connected!"
continue
args = cmd[4:].split(" ")
if len(args) <> 2:
print "Usage: get remotefile localfile"
session.write("cat " + RemoteFile + "\n")
session.read_until("\n") # Skip over command echo
conts = session.read_until("# ").replace("# ", "").strip()
if "No such file or directory" in conts:
print "[Error@Download()] " + args[0] + " does not exist"
else:
if not os.path.exists(args[1]):
os.system("touch " + args[1])
print conts
file = open(args[1], "wb")
file.write(conts)
file.close()
elif cmd.lower()[:3] == "put":
if not connected:
print ">> Not connected!"
continue
args = cmd[4:].split(" ")
if len(args) <> 2:
print "Usage: put localfile rmeotefile"
#elif Upload(cmd[4:]):
#print "Uploaded " + args[0] + " to " + args[1]
# Verify file exists and convert it to a hex stream
if not os.path.exists(LocalFile):
print "[Error@Upload()] " + LocalFile + " does not exist"
return False
# UNFINISHED!
print ">> This command coming soon to a terminal near you!"
elif cmd.lower()[:6] == "status":
if connected:
session.sock.sendall(IAC + NOP + "\n") # What will this do if the connection is closed?? (Probably raise an exception...)
print ">> Connected to " + host
else:
print ">> Not connected"
elif cmd.lower()[:4] == "find":
args = cmd.split(" ")[1:]
srch = "filename"
startDir = "/"
filename = ""
contString = ""
if not connected:
print ">> Not connected"
continue
if len(args) == 0 or len(args) > 3:
print "Usage: find [-c] [STARTDIR] FILENAME|STRING"
print "\tThe -c switch enables contents search, making the last parameter the string to search for."
continue
if len(args) == 1:
# find FILENAME
filename = args[0]
elif len(args) == 2:
if "-c" in args:
# find -c STRING
args.remove("-c")
contString = args[0]
srch = "contents"
else:
# find STARTDIR FILENAME
startDir = args[0]
filename = args[1]
elif len(args) == 3:
# find -c STARTDIR STRING
args.remove("-c")
startDir = args[0]
contsString = args[1]
if startDir[-1] <> "/":
startDir += "/"
stack = [startDir]
# THIS FAILS EPICLY!!!
while len(stack) > 0:
dir = stack.pop()
session.write("ls -Al " + dir + "\n")
conts = session.read_until("# ")
for line in conts.split("\n"):
fields = line.split(" ")
if line[0] == "d":
# Add all subdirectories to the stack for manual recursion
stack.append(dir + fields[-1] + "/")
print "[Debug] " + stack[-1]
elif line[0] == "-":
if srch == "contents":
# Files are either grepped for the search string...
session.write("grep " + contString + " " + filename + "\n")
session.read_until("\n") # Blahblah
resp = session.read_until("# ").replace("# ", "").strip()
if resp <> "":
print resp
elif srch == "filename":
# ...or the filename pattern is checked
if filename.find("*") == -1:
if filename == line[-1]:
print dir + line[-1]
else:
# Implement this later...WAY too lazy/hungry
print "THAT FILTER IS NOT IMPLEMENTED YET! GOD!!"
sys.exit(2) # FUCKING BRUTAL MUCH?! Epic lulz ensued...
else:
if not connected:
print ">> Not connected!"
continue
session.write(cmd + "\n")
session.read_until("\n") # Blahblah
resp = session.read_until("# ").replace("# ", "").strip()
if cmd[:2] == "cd":
session.write("pwd\n")
session.read_until("\n") # Blahblah
cwd = session.read_until("# ").replace("# ", "").strip()
if len(resp) > 0:
print resp
print "Goodbye!"
Init()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment