def main(): with serial.Serial('/dev/ttyAMA0', 115200, timeout=0) as ser: ss = SerialSpawn(ser) # DEBUG ss.logfile = sys.stderr.buffer total_cnt = 0 success_cnt = 0 fail_cnt = 0 first = True log_first = "" logfile = time.strftime("LINUX-LOG-%Y-%m-%d-%H.txt", time.localtime()) f = open(logfile, 'a') f.write("DC_OFF_SECS = {}\n".format(DC_OFF_SECS)) f.write("TIMEOUT_LOGIN = {}\n".format(TIMEOUT_LOGIN)) f.write("TIMEOUT_SHELL = {}\n".format(TIMEOUT_SHELL)) f.write("SHELL_TO_PWROFF = {}\n".format(SHELL_TO_PWROFF)) f.write("TIMEOUT_PWROFF = {}\n".format(TIMEOUT_PWROFF)) power_cycle() tm_start = time.localtime() while True: # try: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # power_cycle() # except TIMEOUT: # pass # power_cycle() # ser_bytes = ser.readline() # print(ser_bytes) ss.sendline() if first: log_first += decode_all(ss) index_login = ss.expect( pattern=[HOSTNAME + ' login:'******'root') elif index_login == 1: # device get stuck print("Wait login TIMEOUT!!!") f.write("Wait login TIMEOUT!!!\n") power_cycle() log_first += decode_all(ss) f.write("### BOOT LOG ###\n" + log_first) f.write("\n\n\n\n\n") continue # ser_bytes = ser.readline() # print(ser_bytes) ss.sendline() if first: log_first += decode_all(ss) index_shell = ss.expect( pattern=['root@' + HOSTNAME + ':', pexpect.TIMEOUT], timeout=TIMEOUT_SHELL) if index_shell == 0: # normal pass elif index_shell == 1: # device get stuck print("Wait shell TIMEOUT!!!") f.write("Wait shell TIMEOUT!!!\n") power_cycle() continue # Wait for system startup complete """ for i in range(SHELL_TO_PWROFF): ss.sendline('systemd-analyze time') index_analyze = ss.expect(pattern=['Startup finished', pexpect.TIMEOUT], timeout = 1) if index_analyze == 0: break time.sleep(1) time.sleep(5) ss.sendline('ifconfig wlan0 down') time.sleep(0.5) ss.sendline('rmmod wlcore_sdio') time.sleep(SHELL_TO_PWROFF - 5) ss.sendline('cpufreq-set -g userspace') time.sleep(0.1) ss.sendline('cpufreq-set -f 300MHz') """ result_success = False if TEST_NETWORK: time.sleep(0.5) ss.sendline('ifconfig eth0 192.168.4.252') time.sleep(2) ss.sendline('ping -c 4 192.168.4.2') index_ping = ss.expect( pattern=['64 bytes from 192.168.4.2', pexpect.TIMEOUT], timeout=4) # print("index_ping = {}\n".format(index_ping)) if index_ping == 0: # found response, OK result_success = True time.sleep(SHELL_TO_PWROFF) time.sleep(0.1) ss.sendline('poweroff') total_cnt = total_cnt + 1 is_repower = TEST_NETWORK if first: log_first += decode_all(ss) index_pwroff = ss.expect( pattern=['reboot: Power down', pexpect.TIMEOUT], timeout=TIMEOUT_PWROFF) tm_pwrdn = time.localtime() if first: log_first += decode_all(ss) if not TEST_NETWORK: index_btldr = ss.expect(pattern=['U-Boot ', pexpect.TIMEOUT], timeout=4) if index_btldr != 0: # no found response, OK result_success = True if not result_success: fail_cnt = fail_cnt + 1 print('____________________________________') print('****** \033[5;31;43m POWER OFF FAILED \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF FAILED!\n") else: success_cnt = success_cnt + 1 is_repower = True print('____________________________________') print('###### \033[1;42m POWER OFF OK! \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF OK!\n") fa = "FAIL : {}\n".format(fail_cnt) ot = "OK/TOTAL : {} / {}\n".format(success_cnt, total_cnt) tm_start_str = time.strftime("%Y-%m-%d %H:%M:%S", tm_start) st = "START : {}\n".format(tm_start_str) ps = time.mktime(tm_pwrdn) - time.mktime(tm_start) cy = "USED : {} Secs\n".format(ps) print(fa + ot + st + cy, end='') print("------------------------------------------------------\n") if first: log_first += decode_all(ss) f.write("### BOOT LOG ###\n" + log_first) f.write("\n\n\n\n\n") f.write(fa + ot + st + cy) f.write( "------------------------------------------------------\n\n") f.flush() if is_repower: power_cycle() tm_start = time.localtime() first = False
def main(): with serial.Serial('/dev/ttyAMA0', 115200, timeout=0) as ser: ss = SerialSpawn(ser) # DEBUG ss.logfile = sys.stderr.buffer total_cnt = 0 success_cnt = 0 fail_cnt = 0 logfile = time.strftime("UBOOT-LOG-%Y-%m-%d.txt", time.localtime()) f = open(logfile, 'a') power_cycle() start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) while True: # try: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # power_cycle() # except TIMEOUT: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # power_cycle() # ser_bytes = ser.readline() # print(ser_bytes) time.sleep(0.1) ss.sendline() index_login = ss.expect( pattern=['CPU : AM335X-GP rev 2.1', pexpect.TIMEOUT], timeout=TIMEOUT_LOGIN) if index_login == 1: # device get stuck print("Device get stuck in index_login.") f.write("Device get stuck in index_login.\r\n") power_cycle() continue # ser_bytes = ser.readline() # print(ser_bytes) for i in range(6): ss.send('\x03') time.sleep(0.3) ss.sendline() index_shell = ss.expect(pattern=['=>', pexpect.TIMEOUT], timeout=TIMEOUT_SHELL) if index_shell == 0: # normal ss.sendline('poweroff') elif index_shell == 1: # device get stuck print("Device get stuck in index_shell.") f.write("Device get stuck in index_shell.\r\n") power_cycle() continue '''record log''' # ret = chardet.detect(data) # print(ret) # s = str(data, encoding = "ascii") # print(type(data)) # print(type(s)) # f.write(s) total_cnt = total_cnt + 1 is_repower = False end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) time.sleep(1) index_btldr = ss.expect(pattern=['U-Boot ', pexpect.TIMEOUT], timeout=TIMEOUT_PWROFF) if index_btldr == 0: fail_cnt = fail_cnt + 1 print('____________________________________') print('****** \033[5;31;43m POWER OFF FAILED \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF FAILED!\r\n") elif index_btldr == 1: # time out = success success_cnt = success_cnt + 1 is_repower = True print('____________________________________') print('###### \033[1;42m POWER OFF OK! \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF OK!\r\n") # print(ss.before) print("total_cnt :", total_cnt) print("success_cnt :", success_cnt) print("fail_cnt :", fail_cnt) print("start time :", start_time) print("end time :", end_time) print("------------------------------------------------------\n") f.write("total_cnt :" + str(total_cnt) + "\r\n") f.write("success_cnt :" + str(success_cnt) + "\r\n") f.write("fail_cnt :" + str(fail_cnt) + "\r\n") f.write("start time :" + start_time + "\r\n") f.write("end time :" + end_time + "\r\n") f.write( "------------------------------------------------------\r\n\r\n" ) f.flush() if is_repower: power_cycle() start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
else: return "" def send_command(console, cmd=''): console.write(cmd + '\r') time.sleep(1) return read_serial(console) send_command(console, cmd='terminal lenght 0') with open("erase_confirm2.txt","a+") as f: for i in conf_commands: f.write(send_command(console, cmd=i)) time.sleep(120) ss = SerialSpawn(console) # Press RETURN to get started. ss.sendline('\r') #Would you like to terminate autoinstall? [yes]: ss.expect('.+yes*') ss.sendline('\r') time.sleep(1) #Would you like to enter the initial configuration dialog? [yes/no]: ss.expect('.+yes/no*') print ss.before ss.sendline('no\r') ss.expect('>') print ss.before ss.logfile = sys.stdout console.close()
def main(): with serial.Serial('/dev/ttyAMA0', 115200, timeout=0) as ser: ss = SerialSpawn(ser) # DEBUG ss.logfile = sys.stderr.buffer total_cnt = 0 success_cnt = 0 fail_cnt = 0 first = True log_first = "" logfile = time.strftime("UBOOT-LOG-%Y-%m-%d-%H.txt", time.localtime()) f = open(logfile, 'a') f.write("DC_OFF_SECS = {}\n".format(DC_OFF_SECS)) f.write("TIMEOUT_LOGIN = {}\n".format(TIMEOUT_LOGIN)) f.write("TIMEOUT_SHELL = {}\n".format(TIMEOUT_SHELL)) f.write("TIMEOUT_PWROFF = {}\n".format(TIMEOUT_PWROFF)) power_cycle() tm_start = time.localtime() while True: # try: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # power_cycle() # except TIMEOUT: # pass # power_cycle() # ser_bytes = ser.readline() # print(ser_bytes) time.sleep(0.1) if first: log_first += decode_all(ss) ss.sendline() index_login = ss.expect( pattern=['CPU : AM335X-GP rev 2.1', pexpect.TIMEOUT], timeout=TIMEOUT_LOGIN) if index_login == 1: # device get stuck print("Wait login TIMEOUT!!!") f.write("Wait login TIMEOUT!!!\n") power_cycle() log_first += decode_all(ss) f.write("### BOOT LOG ###\n" + log_first) f.write("\n\n\n\n\n") continue # ser_bytes = ser.readline() # print(ser_bytes) for i in range(6): ss.send('\x03') time.sleep(0.3) ss.sendline() if first: log_first += decode_all(ss) index_shell = ss.expect(pattern=['=>', pexpect.TIMEOUT], timeout=TIMEOUT_SHELL) if index_shell == 0: # normal pass elif index_shell == 1: # device get stuck print("Wait shell TIMEOUT!!!") f.write("Wait shell TIMEOUT!!!\n") power_cycle() continue ss.sendline('setenv ipaddr 192.168.4.58') time.sleep(0.2) ss.sendline('ping 192.168.4.2') time.sleep(2.0) ss.sendline('poweroff') total_cnt = total_cnt + 1 is_repower = False time.sleep(1) tm_pwrdn = time.localtime() if first: log_first += decode_all(ss) index_btldr = ss.expect(pattern=['U-Boot ', pexpect.TIMEOUT], timeout=TIMEOUT_PWROFF) if first: log_first += decode_all(ss) if index_btldr == 0: fail_cnt = fail_cnt + 1 print('____________________________________') print('****** \033[5;31;43m POWER OFF FAILED \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF FAILED!\n") elif index_btldr == 1: # time out = success success_cnt = success_cnt + 1 is_repower = True print('____________________________________') print('###### \033[1;42m POWER OFF OK! \033[0m') print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') f.write("POWEROFF OK!\n") fa = "FAIL : {}\n".format(fail_cnt) ot = "OK/TOTAL : {} / {}\n".format(success_cnt, total_cnt) tm_start_str = time.strftime("%Y-%m-%d %H:%M:%S", tm_start) st = "START : {}\n".format(tm_start_str) ps = time.mktime(tm_pwrdn) - time.mktime(tm_start) cy = "USED : {} Secs\n".format(ps) print(fa + ot + st + cy, end='') print("------------------------------------------------------\n") if first: log_first += decode_all(ss) f.write("### BOOT LOG ###\n" + log_first) f.write("\n\n\n\n\n") f.write(fa + ot + st + cy) f.write( "------------------------------------------------------\n\n") f.flush() if is_repower: power_cycle() tm_start = time.localtime() first = False
def main(): global logfile AP_ESCAPE = "Escape character is '^]'." AP_USERNAME = "******" AP_PASSWORD = "******" AP_EN = "en" AP_MORE = "--More--" AP_EXIT = "exit" LF_PROMPT = "$" CR = "\r\n" parser = argparse.ArgumentParser(description="Cisco AP Control Script") parser.add_argument("-a", "--prompt", type=str, help="ap prompt") parser.add_argument("-d", "--dest", type=str, help="address of the AP 172.19.27.55") parser.add_argument("-o", "--port", type=int, help="control port on the AP, 2008") parser.add_argument("-u", "--user", type=str, help="credential login/username, admin") parser.add_argument("-p", "--passwd", type=str, help="credential password Wnbulab@123") parser.add_argument("-s", "--scheme", type=str, choices=["serial", "ssh", "telnet"], help="Connect via serial, ssh or telnet") parser.add_argument("-t", "--tty", type=str, help="tty serial device for connecting to AP") parser.add_argument("-l", "--log", type=str, help="logfile for messages, stdout means output to console",default="stdout") parser.add_argument("-z", "--action", type=str, help="action, current action is powercfg") parser.add_argument("-b", "--baud", type=str, help="action, baud rate lanforge: 115200 cisco: 9600") args = None try: args = parser.parse_args() host = args.dest scheme = args.scheme port = (default_ports[scheme], args.port)[args.port != None] user = args.user if (args.log != None): logfile = args.log except Exception as e: logging.exception(e) usage() exit(2) console_handler = logging.StreamHandler() formatter = logging.Formatter(FORMAT) logg = logging.getLogger(__name__) logg.setLevel(logging.DEBUG) file_handler = None if (logfile is not None): if (logfile != "stdout"): file_handler = logging.FileHandler(logfile, "w") file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logg.addHandler(file_handler) logging.basicConfig(format=FORMAT, handlers=[file_handler]) else: # stdout logging logging.basicConfig(format=FORMAT, handlers=[console_handler]) egg = None # think "eggpect" ser = None try: if (scheme == "serial"): #eggspect = pexpect.fdpexpect.fdspan(telcon, logfile=sys.stdout.buffer) ser = serial.Serial(args.tty, int(args.baud), timeout=5) print("Created serial connection on %s, open: %s"%(args.tty, ser.is_open)) egg = SerialSpawn(ser) egg.logfile = FileAdapter(logg) time.sleep(1) egg.sendline(CR) time.sleep(1) elif (scheme == "ssh"): if (port is None): port = 22 cmd = "ssh -p%d %s@%s"%(port, user, host) logg.info("Spawn: "+cmd+NL) egg = pexpect.spawn(cmd) #egg.logfile_read = sys.stdout.buffer egg.logfile = FileAdapter(logg) elif (scheme == "telnet"): if (port is None): port = 23 cmd = "telnet {} {}".format(host, port) logg.info("Spawn: "+cmd+NL) egg = pexpect.spawn(cmd) egg.logfile = FileAdapter(logg) # Will login below as needed. else: usage() exit(1) except Exception as e: logging.exception(e) AP_PROMPT = "{}>".format(args.prompt) AP_HASH = "{}#".format(args.prompt) time.sleep(0.1) logged_in = False loop_count = 0 while (loop_count <= 8 and logged_in == False): loop_count += 1 i = egg.expect_exact([AP_ESCAPE,AP_PROMPT,AP_HASH,AP_USERNAME,AP_PASSWORD,AP_MORE,LF_PROMPT,pexpect.TIMEOUT],timeout=5) if i == 0: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_ESCAPE,i,egg.before,egg.after)) egg.sendline(CR) # Needed after Escape or should just do timeout and then a CR? sleep(1) if i == 1: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_PROMPT,i,egg.before,egg.after)) egg.sendline(AP_EN) sleep(1) j = egg.expect_exact([AP_PASSWORD,pexpect.TIMEOUT],timeout=5) if j == 0: logg.info("Expect: {} i: {} j: {} before: {} after: {}".format(AP_PASSWORD,i,j,egg.before,egg.after)) egg.sendline(args.passwd) sleep(1) k = egg.expect_exact([AP_HASH,pexpect.TIMEOUT],timeout=5) if k == 0: logg.info("Expect: {} i: {} j: {} k: {} before: {} after: {}".format(AP_PASSWORD,i,j,k,egg.before,egg.after)) logged_in = True if k == 1: logg.info("Expect: {} i: {} j: {} k: {} before: {} after: {}".format("Timeout",i,j,k,egg.before,egg.after)) if j == 1: logg.info("Expect: {} i: {} j: {} before: {} after: {}".format("Timeout",i,j,egg.before,egg.after)) if i == 2: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_HASH,i,egg.before,egg.after)) logged_in = True sleep(1) if i == 3: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_USERNAME,i,egg.before,egg.after)) egg.sendline(args.user) sleep(1) if i == 4: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_PASSWORD,i,egg.before,egg.after)) egg.sendline(args.passwd) sleep(1) if i == 5: logg.info("Expect: {} i: {} before: {} after: {}".format(AP_MORE,i,egg.before,egg.after)) if (scheme == "serial"): egg.sendline("r") else: egg.sendcontrol('c') sleep(1) # for Testing serial connection using Lanforge if i == 6: logg.info("Expect: {} i: {} before: {} after: {}".format(LF_PROMPT,i,egg.before.decode('utf-8', 'ignore'),egg.after.decode('utf-8', 'ignore'))) if (loop_count < 3): egg.send("ls -lrt") sleep(1) if (loop_count > 4): logged_in = True # basically a test mode using lanforge serial if i == 7: logg.info("Expect: {} i: {} before: {} after: {}".format("Timeout",i,egg.before,egg.after)) egg.sendline(CR) sleep(1) if (args.action == "powercfg"): logg.info("execute: show controllers dot11Radio 1 powercfg | g T1") egg.sendline('show controllers dot11Radio 1 powercfg | g T1') egg.expect([pexpect.TIMEOUT], timeout=3) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output i = egg.expect_exact([AP_MORE,pexpect.TIMEOUT],timeout=5) if i == 0: egg.sendcontrol('c') if i == 1: logg.info("send cntl c anyway") egg.sendcontrol('c') elif (args.action == "clear_log"): logg.info("execute: clear log") egg.sendline('clear log') sleep(0.4) egg.sendline('show log') egg.expect([pexpect.TIMEOUT], timeout=2) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output # allow for normal logout below elif (args.action == "show_log"): logg.info("execute: show log") egg.sendline('show log') sleep(0.4) egg.expect([pexpect.TIMEOUT], timeout=2) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output i = egg.expect_exact([AP_MORE,pexpect.TIMEOUT],timeout=4) if i == 0: egg.sendline('r') egg.expect([pexpect.TIMEOUT], timeout=4) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output if i == 1: print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output # allow for normal logout below # show log | g DOT11_DRV # CAC_EXPIRY_EVT: CAC finished on DFS channel 52 elif (args.action == "cac_expiry_evt"): logg.info("execute: show log | g CAC_EXPIRY_EVT") egg.sendline('show log | g CAC_EXPIRY_EVT') sleep(0.4) egg.expect([pexpect.TIMEOUT], timeout=2) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output i = egg.expect_exact([AP_MORE,pexpect.TIMEOUT],timeout=4) if i == 0: egg.sendline('r') egg.expect([pexpect.TIMEOUT], timeout=4) # do not delete this for it allows for subprocess to see output print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output if i == 1: print(egg.before.decode('utf-8', 'ignore')) # do not delete this for it allows for subprocess to see output elif (args.action == "ds_data_5ghz"): logg.info("execute: wl -i wl1 bs_data") egg.sendline('wl -i wl1 bs_data') egg.expect([pexpect.TIMEOUT], timeout=4) # do not detete this for it allow for subprocess to read print(egg.before.decode('utf-8','ignore')) # do not delete this for it allows for subprocess to see output elif (args.action == "ds_data_24ghz"): logg.info("execute: wl -i wl0 bs_data") egg.sendline('wl -i wl1 bs_data') egg.expect([pexpect.TIMEOUT], timeout=4) # do not detete this for it allow for subprocess to read print(egg.before.decode('utf-8','ignore')) # do not delete this for it allows for subprocess to see output else: # no other command at this time so send the same power command #logg.info("no action so execute: show controllers dot11Radio 1 powercfg | g T1") logg.info("no action") i = egg.expect_exact([AP_PROMPT,AP_HASH,pexpect.TIMEOUT],timeout=1) if i == 0: logg.info("received {} we are done send exit".format(AP_PROMPT)) egg.sendline(AP_EXIT) if i == 1: logg.info("received {} send exit".format(AP_HASH)) egg.sendline(AP_EXIT) if i == 2: logg.info("timed out waiting for {} or {}".format(AP_PROMPT,AP_HASH))
def main(): global prompt parser = argparse.ArgumentParser(description="OpenWrt AP Control Script") parser.add_argument("-d", "--dest", type=str, help="address of the cisco controller") parser.add_argument("-o", "--port", type=int, help="control port on the controller") parser.add_argument("-u", "--user", type=str, help="credential login/username") parser.add_argument("-p", "--passwd", type=str, help="credential password") parser.add_argument("-P", "--prompt", type=str, help="Prompt to look for") parser.add_argument("-s", "--scheme", type=str, choices=["serial", "ssh", "telnet"], help="Connect via serial, ssh or telnet") parser.add_argument("-t", "--tty", type=str, help="tty serial device") parser.add_argument( "-l", "--log", type=str, help="logfile for messages, stdout means output to console") parser.add_argument("--action", type=str, help="perform action", choices=[ "logread", "journalctl", "lurk", "sysupgrade", "download", "upload", "reboot", "cmd" ]) parser.add_argument("--value", type=str, help="set value") parser.add_argument("--value2", type=str, help="set value2") tty = None args = None try: args = parser.parse_args() host = args.dest scheme = args.scheme port = args.port #port = (default_ports[scheme], args.port)[args.port != None] user = args.user passwd = args.passwd logfile = args.log tty = args.tty if (args.prompt != None): prompt = args.prompt filehandler = None except Exception as e: logging.exception(e) usage() exit(2) console_handler = logging.StreamHandler() formatter = logging.Formatter(FORMAT) logg = logging.getLogger(__name__) logg.setLevel(logging.DEBUG) file_handler = None if (logfile is not None): if (logfile != "stdout"): file_handler = logging.FileHandler(logfile, "w") file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logg.addHandler(file_handler) logging.basicConfig(format=FORMAT, handlers=[file_handler]) else: # stdout logging logging.basicConfig(format=FORMAT, handlers=[console_handler]) CCPROMPT = prompt ser = None egg = None # think "eggpect" try: if (scheme == "serial"): #eggspect = pexpect.fdpexpect.fdspan(telcon, logfile=sys.stdout.buffer) import serial from pexpect_serial import SerialSpawn ser = serial.Serial(tty, 115200, timeout=5) egg = SerialSpawn(ser) egg.logfile = FileAdapter(logg) egg.sendline(NL) try: i = egg.expect( [prompt, "Please press Enter to activate", "login:"******"Password:"******"ssh"): # Not implemented/tested currently. --Ben if (port is None): port = 22 cmd = "ssh -p%d %s@%s" % (port, user, host) logg.info("Spawn: " + cmd + NL) egg = pexpect.spawn(cmd) #egg.logfile_read = sys.stdout.buffer egg.logfile = FileAdapter(logg) i = egg.expect(["password:"******"continue connecting (yes/no)?"], timeout=3) time.sleep(0.1) if i == 1: egg.sendline('yes') egg.expect('password:'******' ') egg.expect('User\:') egg.sendline(user) egg.expect('Password\:') egg.sendline(passwd) egg.sendline('config paging disable') else: usage() exit(1) except Exception as e: logging.exception(e) command = None CLOSEDBYREMOTE = "closed by remote host." CLOSEDCX = "Connection to .* closed." try: egg.expect(CCPROMPT) except Exception as e: egg.sendline(NL) TO = 10 wait_forever = False # Clean pending output egg.sendline("echo __hello__") egg.expect("__hello__") egg.expect(CCPROMPT) logg.info("Action[%s] Value[%s] Value2[%s]" % (args.action, args.value, args.value2)) if (args.action == "reboot"): command = "reboot" TO = 60 if (args.action == "cmd"): if (args.value is None): raise Exception("cmd requires value to be set.") command = "%s" % (args.value) if (args.action == "logread"): command = "logread -f" TO = 1 wait_forever = True if (args.action == "journalctl"): command = "journalctl -f" TO = 1 wait_forever = True if (args.action == "lurk"): command = "date" TO = 1 wait_forever = True if (args.action == "sysupgrade"): command = "scp %s /tmp/new_img.bin" % (args.value) logg.info("Command[%s]" % command) egg.sendline(command) i = egg.expect(["password:"******"Do you want to continue connecting"], timeout=5) if i == 1: egg.sendline("y") egg.expect("password:"******"lanforge") egg.expect(CCPROMPT, timeout=20) egg.sendline("sysupgrade /tmp/new_img.bin") egg.expect("link becomes ready", timeout=100) return if (args.action == "download"): command = "scp %s /tmp/%s" % (args.value, args.value2) logg.info("Command[%s]" % command) egg.sendline(command) i = egg.expect([ "password:"******"Do you want to continue connecting", "Network unreachable" ], timeout=5) if i == 2: print("Network unreachable, wait 15 seconds and try again.") time.sleep(15) command = "scp %s /tmp/%s" % (args.value, args.value2) logg.info("Command[%s]" % command) egg.sendline(command) i = egg.expect([ "password:"******"Do you want to continue connecting", "Network unreachable" ], timeout=5) if i == 2: print("ERROR: Could not connect to LANforge to get download file") exit(2) if i == 1: egg.sendline("y") egg.expect("password:"******"lanforge") egg.expect(CCPROMPT, timeout=20) return if (args.action == "upload"): command = "scp %s %s" % (args.value, args.value2) logg.info("Command[%s]" % command) egg.sendline(command) i = egg.expect([ "password:"******"Do you want to continue connecting", "Network unreachable" ], timeout=5) if i == 2: print("Network unreachable, wait 15 seconds and try again.") time.sleep(15) command = "scp /tmp/%s %s" % (args.value, args.value2) logg.info("Command[%s]" % command) egg.sendline(command) i = egg.expect([ "password:"******"Do you want to continue connecting", "Network unreachable" ], timeout=5) if i == 2: print("ERROR: Could not connect to LANforge to put upload file") exit(2) if i == 1: egg.sendline("y") egg.expect("password:"******"lanforge") egg.expect(CCPROMPT, timeout=20) return if (command is None): logg.info("No command specified, going to log out.") else: logg.info("Command[%s]" % command) egg.sendline(command) while True: try: i = egg.expect( [CCPROMPT, "kmodloader: done loading kernel", "\n"], timeout=TO) print(egg.before.decode('utf-8', 'ignore')) if i == 1: egg.sendline(' ') egg.expect(CCPROMPT, timeout=20) print(egg.before.decode('utf-8', 'ignore')) if i == 2: # new line of text, just print and continue continue if not wait_forever: break except Exception as e: # Some commands take a long time (logread -f) if not wait_forever: logging.exception(e) break
def main(): parser = argparse.ArgumentParser(description="Cisco AP Control Script") parser.add_argument("-d", "--dest", type=str, help="address of the cisco controller") parser.add_argument("-o", "--port", type=int, help="control port on the controller") parser.add_argument("-u", "--user", type=str, help="credential login/username") parser.add_argument("-p", "--passwd", type=str, help="credential password") parser.add_argument("-s", "--scheme", type=str, choices=["serial", "ssh", "telnet"], help="Connect via serial, ssh or telnet") parser.add_argument("-t", "--tty", type=str, help="tty serial device") parser.add_argument( "-l", "--log", type=str, help="logfile for messages, stdout means output to console") #parser.add_argument("-r", "--radio", type=str, help="select radio") parser.add_argument("-a", "--ap", type=str, help="select AP") parser.add_argument("-b", "--band", type=str, help="Select band (a | b | abgn)", choices=["a", "b", "abgn"]) parser.add_argument("--action", type=str, help="perform action", choices=[ "config", "country", "ap_country", "enable", "disable", "summary", "advanced", "cmd", "txPower", "bandwidth", "channel", "show" ]) parser.add_argument("--value", type=str, help="set value") args = None try: args = parser.parse_args() host = args.dest scheme = args.scheme port = (default_ports[scheme], args.port)[args.port != None] user = args.user passwd = args.passwd logfile = args.log if (args.band != None): band = args.band if (band == "abgn"): band = "-abgn" else: band = "a" filehandler = None except Exception as e: logging.exception(e) usage() exit(2) console_handler = logging.StreamHandler() formatter = logging.Formatter(FORMAT) logg = logging.getLogger(__name__) logg.setLevel(logging.DEBUG) file_handler = None if (logfile is not None): if (logfile != "stdout"): file_handler = logging.FileHandler(logfile, "w") file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) logg.addHandler(file_handler) logging.basicConfig(format=FORMAT, handlers=[file_handler]) else: # stdout logging logging.basicConfig(format=FORMAT, handlers=[console_handler]) egg = None # think "eggpect" try: if (scheme == "serial"): #eggspect = pexpect.fdpexpect.fdspan(telcon, logfile=sys.stdout.buffer) import serial from pexpect_serial import SerialSpawn with serial.Serial('/dev/ttyUSB0', 115200, timeout=5) as ser: egg = SerialSpawn(ser) egg.logfile = FileAdapter(logg) egg.sendline(NL) time.sleep(0.1) egg.expect('login:'******'password:'******'yes') egg.expect('password:'******'login:'******'password:'******'\(Cisco Controller\) >' EXITPROMPT = "Would you like to save them now\? \(y/N\)" AREYOUSURE = "Are you sure you want to continue\? \(y/n\)" CLOSEDBYREMOTE = "closed by remote host." CLOSEDCX = "Connection to .* closed." egg.expect(CCPROMPT) logg.info("Ap[%s] Action[%s] Value[%s] " % (args.ap, args.action, args.value)) if ((args.action == "show") and (args.value is None)): raise Exception("show requires value, like 'country' or 'ap summary'") if (args.action == "show"): #print ("HI") command = "show " + args.value if (args.action == "cmd"): if (args.value is None): raise Exception("cmd requires value to be set.") command = "%s" % (args.value) if (args.action == "summary"): command = "show ap summary" if (args.action == "advanced"): command = "show advanced 802.11%s summary" % (band) if ((args.action == "ap_country") and ((args.value is None) or (args.ap is None))): raise Exception("ap_country requires country and AP name") if (args.action == "ap_country"): command = "config ap country %s %s" % (args.value, args.ap) if ((args.action == "country") and ((args.value is None))): raise Exception("country requires country value") if (args.action == "country"): command = "config country %s" % (args.value) if (args.action in ["enable", "disable"] and (args.ap is None)): raise Exception("action requires AP name") if (args.action == "enable"): command = "config 802.11%s enable %s" % (band, args.ap) if (args.action == "disable"): command = "config 802.11%s disable %s" % (band, args.ap) if (args.action == "txPower" and ((args.ap is None) or (args.value is None))): raise Exception("txPower requires ap and value") if (args.action == "txPower"): command = "config 802.11%s txPower ap %s %s" % (band, args.ap, args.value) if (args.action == "bandwidth" and ((args.ap is None) or (args.value is None))): raise Exception("bandwidth requires ap and value (20, 40, 80, 160)") if (args.action == "bandwidth"): command = "config 802.11%s chan_width %s %s" % (band, args.ap, args.value) if (args.action == "channel" and ((args.ap is None) or (args.value is None))): raise Exception("channel requires ap and value") if (args.action == "channel"): command = "config 802.11%s channel ap %s %s" % (band, args.ap, args.value) if (command is None): logg.info("No command specified, going to log out.") else: logg.info("Command[%s]" % command) egg.sendline(command) while True: i = egg.expect([CCPROMPT, AREYOUSURE, '--More-- or']) print(egg.before.decode('utf-8', 'ignore')) if i == 0: break if i == 1: egg.sendline("y") break if i == 2: egg.sendline(NL) egg.sendline("logout") i = egg.expect([EXITPROMPT, CLOSEDBYREMOTE, CLOSEDCX]) if i == 0: egg.sendline("y")