#!/usr/bin/python
"""
This very simple program allows to upload a file to a remote host when there's
no FTP/WEB/whatever client or server, but you have a shell. It uses "echo -ne"
invokations to create the remote file. To run it, modify the host, port, dstbin
and chat parameters below, and start it like that :

$ python octify.py < file_to_upload

Warning, it's quite slow, so don't even think about uploading large files with
it unless you have a lot of time ... You should rather use it to upload a
simple network client (tftp, or maybe a simplified wget), and then use this
client.

This code was wrote by Jerome Petazzoni <jp at enix dot org> and is placed
under GPL license.
"""
import sys,socket

# you can modify those parameters
host="192.168.1.1"
port=23
verbose=0 # set to 1 to see telnet responses
dstbin="/var/run/upload" # file to create on the remote host
chat=[("Login:","admin\n"),("Password:","admin\n"),("> ","sh\n")]

# normally you don't need to modify those
prompt="# "
batch=20
data=sys.stdin.read()
length=len(data)
octs=["\\%03o"%ord(o) for o in data]

# read data from the socket and display it if we're in verbose mode
def feed():
	data=s.recv(1024)
	if verbose: sys.stdout.write(data)
	return data

# connect to the target
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))

# initial chat (send login, password, sh command)
buffer=""
for expect,answer in chat:
	while expect not in buffer: buffer+=feed()
	buffer=""
	s.send(answer)

# erase the file in case it already exists
while prompt not in buffer: buffer+=feed()
buffer=""
s.send('echo -ne "" >%s\n'%dstbin)

# "upload" the file
while octs:
	next,octs=octs[:batch],octs[batch:]
	while prompt not in buffer: buffer+=feed()
	buffer=""
	s.send("echo -ne '%s' >>%s\n"%("".join(next),dstbin))
	print "%d/%d"%(length-len(octs),length)

# wait for final prompt
while prompt not in buffer: buffer+=feed()
buffer=""
print "DONE"
	
