#!/usr/bin/env python

# Python script for nat loopback on a
# ZTE Modem with a busybox firmware installed. All it does is
# add an iptables rule for that, but without requiring expect.
#
from socket import *
import time

sltime = 0.5

# variables for communication
host = '192.168.1.1'
port = 23
user = 'admin'
password = 'blahyadda'
bufsize = 2048 

# more variables; these correspond to the standardized input
# that comes from busybox
loginstr = 'Login: '
passstr = 'Password: '
shellstr = '> '
rootstr = '# '

# stuff that i'm sending to the router
shcomm = 'sh'
iprule1 = 'iptables -t nat -A PREROUTING -d 92.86.141.4' 
iprule1 += ' -p tcp --dport 80 -j DNAT --to 192.168.1.2'
iprule2 = 'iptables -t nat -A POSTROUTING -d 192.168.1.2 -s 192.168.1.0/24'
iprule2 += ' -p tcp --dport 80 -j SNAT --to 192.168.1.1'
exitcomm = 'exit'

addr = (host,port)

# Command list
l = [shcomm,iprule1,iprule2,exitcomm]

def rcvshell(sock,expect):
    if expect:
        exp = sock.recv(len(expect))
        if exp != expect:
            print "Expected:", expect
            print "Received:", exp
            exit(-1)
    else: exp = sock.recv(bufsize)
    return exp

def sndshell(sock,sdata):
    sock.send(sdata)
    sock.send('\r')
    time.sleep(sltime)

# the socket
sock = socket(AF_INET,SOCK_STREAM)
sock.connect(addr)

# the communication itself
data = sock.recv(bufsize) #ignore this part

# not ignoring characters in the login part
rcvshell(sock,loginstr)
sndshell(sock,user)
rcvshell(sock,user + '\r\n')
rcvshell(sock,passstr)
sndshell(sock,password + '\r')
rcvshell(sock,'\r\n')
rcvshell(sock,shellstr)

# here be commands
for str in l:
    sndshell(sock,str)
    data = rcvshell(sock,None)
    print data

sock.close()
