#!/usr/bin/env python3

import argparse
import logging
import telnetlib
import time

TELNET_PORT = 23
TIMEOUT = 5

logging.basicConfig(#level=logging.DEBUG,
                    format='[%(levelname)s] [%(asctime)s] %(message)s',
                    datefmt='%Y-%m-%d %H:%M')

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('host')
    parser.add_argument('-u', '--username', '--user')
    parser.add_argument('-p', '--password', '--pass')
    parser.add_argument('--userkey')
    parser.add_argument('--passkey')
    parser.add_argument('command', nargs='+')

    args = parser.parse_args()
   
    if '@' in args.host:
        args.username, args.host = args.host.split('@')
    else:
        args.username = None
    
    if ':' in args.host:
        args.host, args.port = args.host.split(':')
    else:
        args.port = TELNET_PORT
        
    args.userkey = args.userkey or 'Login'
    args.passkey = args.passkey or 'Password'
    
    args.userkey = args.userkey.encode()
    args.passkey = args.passkey.encode()
    
    return args

args = get_args()

host, port = args.host, args.port
username, password = args.username, args.password
command = ' '.join(args.command)

tel = telnetlib.Telnet(host, port, timeout=TIMEOUT)

if username is not None:
    logging.debug(tel.read_until(b'Login'))
    tel.write(username.encode('ascii') + b'\r\n')
    
if password is not None:
    logging.debug(tel.read_until(b'Password'))
    tel.write(password.encode('ascii') + b'\r\n')

tel.write(command.encode('ascii') + b'\r\n')
time.sleep(0.5) # give time for embedded processor to send over socket

if logging.getLogger().getEffectiveLevel() <= logging.DEBUG:
    logging.debug(tel.get_socket().recv(8192))

tel.close()
