def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() if self._task.environment and any(self._task.environment): display.warning('The serialport task does not support the environment keyword') result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect if self._play_context.check_mode: # in --check mode, always skip this module execution result['skipped'] = True result['msg'] = 'The serialport task does not support check mode' else: result['changed'] = True result['failed'] = False serial_device = self._task.args.get('serial_device', u'/dev/ttyUSB0') serial_rate = self._task.args.get('serial_rate', 115200) command = self._task.args.get('command') echo = self._task.args.get('echo', False) timeout = self._task.args.get('timeout', 30) responses = self._task.args.get('responses') with serial.Serial(serial_device, serial_rate, timeout=0) as ser: ss = SerialSpawn(ser) ss.sendline(command) for key, value in responses.items(): display.v('key: {} value: {}'.format(key, value)) ss.expect(key) ss.sendline(value) return dict()
class ExpectSerial(object): def __init__(self, serial, logfile=None): self.logfile = logfile self.serial = serial self.child = SerialSpawn(serial, logfile=logfile, maxread=1) def respawn(self): self.child = SerialSpawn(self.serial, logfile=self.logfile, maxread=1) def is_detached_uut(self): return True def sendline(self, s): self.child.sendline(s) def flush(self): self.child.flush() def read_nonblocking(self, size=1, timeout=-1): return self.child.read_nonblocking(size, timeout) def expect(self, regex_list, timeout=-1, searchwindowsize=-1): return self.child.expect(regex_list, timeout=timeout, searchwindowsize=searchwindowsize) def expect_str(self, string_list, timeout=-1, searchwindowsize=-1): return self.child.expect_exact(string_list, timeout=timeout, searchwindowsize=searchwindowsize) def get_before(self): r = self.child.before if (isinstance(r, bytes) == True): r = str(r, 'utf-8') return r def get_after(self): r = self.child.after if (isinstance(r, bytes) == True): r = str(r, 'utf-8') return r def close(self): self.child.close()
def ap_action(self): print("ap_cmd: {}".format(self.ap_cmd)) try: ser = serial.Serial(self.ap_port, int(self.ap_baud), timeout=5) ss = SerialSpawn(ser) ss.sendline(str(self.ap_cmd)) ss.expect([pexpect.TIMEOUT], timeout=2) # do not detete line, waits for output ap_results = ss.before.decode('utf-8', 'ignore') print("ap_results {}".format(ap_results)) except: ap_results = "exception on accessing {} Command: {}\r\n".format(self.ap_port, self.ap_cmd) print("{}".format(ap_results)) if self.ap_file is not None: ap_file = open(str(self.ap_file), "a") ap_file.write(ap_results) ap_file.close() print("ap file written {}".format(str(self.ap_file)))
class OpenThreadController(object): """This is an simple wrapper to communicate with openthread""" def __init__(self, port, log=False): """Initialize the controller Args: port (str): serial port's path or name(windows) """ self.port = port self._log = log self._ss = None self._lv = None self._init() def _init(self): ser = serial.Serial(self.port, 115200, timeout=2, xonxoff=True) self._ss = SerialSpawn(ser, timeout=2) if not self._log: return if self._lv: self._lv.stop() self._lv = OpenThreadLogViewer(ss=self._ss) self._lv.start() def __del__(self): self.close() def close(self): if self._lv and self._lv.is_alive(): self._lv.viewing = False self._lv.join() if self._ss: self._ss.close() def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def is_started(self): """check if openthread is started Returns: bool: started or not """ state = self._req('state')[0] return state != 'disabled' def start(self): """Start openthread """ self._req('ifconfig up') self._req('thread start') def stop(self): """Stop openthread """ self._req('thread stop') self._req('ifconfig down') def reset(self): """Reset openthread device, not equivalent to stop and start """ logger.info('DUT> reset') self._log and self._lv.pause() self._ss.sendline('reset') self._log and self._lv.resume() def _req(self, req): """Send command and wait for response. The command will be repeated 3 times at most in case data loss of serial port. Args: req (str): Command to send, please do not include new line in the end. Returns: [str]: The output lines """ logger.info('DUT> %s', req) self._log and self._lv.pause() times = 3 res = None while times: times = times - 1 try: self._ss.sendline(req) self._ss.expect(req + self._ss.linesep) line = None res = [] while True: line = self._ss.readline().strip('\0\r\n\t ') logger.debug(line) if line == 'Done': break if line: res.append(line) break except: logger.exception('Failed to send command') self.close() self._init() self._log and self._lv.resume() return res @property def networkname(self): """str: Thread network name.""" return self._req('networkname')[0] @networkname.setter def networkname(self, value): self._req('networkname %s' % value) @property def mode(self): """str: Thread mode.""" return self._req('mode')[0] @mode.setter def mode(self, value): self._req('mode %s' % value) @property def mac(self): """str: MAC address of the device""" return self._req('extaddr')[0] @property def addrs(self): """[str]: IP addresses of the devices""" return self._req('ipaddr') @property def short_addr(self): """str: Short address""" return self._req('rloc16')[0] @property def channel(self): """int: Channel number of openthread""" return int(self._req('channel')[0]) @channel.setter def channel(self, value): self._req('channel %d' % value) @property def panid(self): """str: Thread panid""" return self._req('panid')[0] @panid.setter def panid(self, value): self._req('panid %s' % value) @property def extpanid(self): """str: Thread extpanid""" return self._req('extpanid')[0] @extpanid.setter def extpanid(self, value): self._req('extpanid %s' % value) @property def child_timeout(self): """str: Thread child timeout in seconds""" return self._req('childtimeout')[0] @child_timeout.setter def child_timeout(self, value): self._req('childtimeout %d' % value) @property def version(self): """str: Open thread version""" return self._req('version')[0] def add_prefix(self, prefix, flags, prf): """Add network prefix. Args: prefix (str): network prefix. flags (str): network prefix flags, please refer thread documentation for details prf (str): network prf, please refer thread documentation for details """ self._req('prefix add %s %s %s' % (prefix, flags, prf)) time.sleep(1) self._req('netdataregister') def remove_prefix(self, prefix): """Remove network prefix. """ self._req('prefix remove %s' % prefix) time.sleep(1) self._req('netdataregister') def enable_blacklist(self): """Enable blacklist feature""" self._req('blacklist enable') def add_blacklist(self, mac): """Add a mac address to blacklist""" self._req('blacklist add %s' % mac)
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())
class OpenThreadController(object): """This is an simple wrapper to communicate with openthread""" def __init__(self, port): """Initialize the controller Args: port (str): serial port's path or name(windows) """ self.port = port self.ss = None self._init() def _init(self): ser = serial.Serial(self.port, 115200, timeout=2) self.ss = SerialSpawn(ser, timeout=2) def __del__(self): if self.ss: self.ss.close() def is_started(self): """check if openthread is started Returns: bool: started or not """ state = self._req('state')[0] return state != 'disabled' def start(self): """Start openthread """ self._req('ifconfig up') self._req('thread start') def stop(self): """Stop openthread """ self._req('thread stop') self._req('ifconfig down') def reset(self): """Reset openthread device, not equivalent to stop and start """ self.ss.sendline('reset') time.sleep(1) self.ss.close() time.sleep(1) self._init() def _req(self, req): """Send command and wait for response. The command will be repeated 3 times at most in case data loss of serial port. Args: req (str): Command to send, please do not include new line in the end. Returns: [str]: The output lines """ logger.info('DUT> %s', req) times = 3 while times: times = times - 1 try: self.ss.sendline(req) self.ss.expect(req + self.ss.linesep) except: logger.exception('Failed to send command') else: break line = None res = [] while True: line = self.ss.readline().strip('\0\r\n\t ') logger.debug(line) if line: if line == 'Done': break res.append(line) return res @property def networkname(self): """str: Thread network name.""" return self._req('networkname')[0] @networkname.setter def networkname(self, value): self._req('networkname %s' % value) @property def mode(self): """str: Thread mode.""" return self._req('mode')[0] @mode.setter def mode(self, value): self._req('mode %s' % value) @property def mac(self): """str: MAC address of the device""" return self._req('extaddr')[0] @property def addrs(self): """[str]: IP addresses of the devices""" return self._req('ipaddr') @property def short_addr(self): """str: Short address""" return self._req('rloc16')[0] @property def channel(self): """int: Channel number of openthread""" return int(self._req('channel')[0]) @channel.setter def channel(self, value): self._req('channel %d' % value) @property def panid(self): """str: Thread panid""" return self._req('panid')[0] @panid.setter def panid(self, value): self._req('panid %s' % value) @property def extpanid(self): """str: Thread extpanid""" return self._req('extpanid')[0] @extpanid.setter def extpanid(self, value): self._req('extpanid %s' % value) @property def child_timeout(self): """str: Thread child timeout in seconds""" return self._req('childtimeout')[0] @child_timeout.setter def child_timeout(self, value): self._req('childtimeout %d' % value) @property def version(self): """str: Open thread version""" return self._req('version')[0] def add_prefix(self, prefix, flags, prf): """Add network prefix. Args: prefix (str): network prefix. flags (str): network prefix flags, please refer thread documentation for details prf (str): network prf, please refer thread documentation for details """ self._req('prefix add %s %s %s' % (prefix, flags, prf)) time.sleep(1) self._req('netdataregister') def remove_prefix(self, prefix): """Remove network prefix. """ self._req('prefix remove %s' % prefix) time.sleep(1) self._req('netdataregister')
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) total_cnt = 0 success_cnt = 0 fail_cnt = 0 GPIO.output(Pin_Relay, GPIO.LOW) f = open("./logfile1.txt", 'a') while True: # try: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # GPIO.output(Pin_Relay, GPIO.HIGH) # time.sleep(2) # GPIO.output(Pin_Relay, GPIO.LOW) # time.sleep(2) # except TIMEOUT: # a = ss.expect('SCHNEIDER2 login:'******'root') # b = ss.expect('root@SCHNEIDER2:') # ss.sendline('poweroff') # GPIO.output(Pin_Relay, GPIO.HIGH) # time.sleep(2) # GPIO.output(Pin_Relay, GPIO.LOW) # time.sleep(2) # ser_bytes = ser.readline() # print(ser_bytes) start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ss.expect(pattern='SCHNEIDER2 login:'******'root') # print(ss.before) # ser_bytes = ser.readline() # print(ser_bytes) # ser_bytes = ser.readline() # print(ser_bytes) ss.expect(pattern='root@SCHNEIDER2:', timeout=10000) ss.sendline('poweroff') # print(ss.before) '''record log''' # data = ss.before # 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 index = ss.expect( pattern=['Trying to boot from MMC1', pexpect.TIMEOUT], timeout=30) if (index == 0): fail_cnt = fail_cnt + 1 print('This test is\033[1;31m fail\033[0m!') ss.expect(pattern='SCHNEIDER2 login:'******'root') # print(ss.before) ss.expect(pattern='root@SCHNEIDER2:', timeout=10000) ss.sendline('poweroff') # print(ss.before) time.sleep(20) f.write("This test is fail!") f.write("\r\n") elif (index == 1): success_cnt = success_cnt + 1 print("This test is successful!") f.write("This test is successful!") f.write("\r\n") end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 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)) f.write("\r\n") f.write("success_cnt :" + str(success_cnt)) f.write("\r\n") f.write("fail_cnt :" + str(fail_cnt)) f.write("\r\n") f.write("start time :" + start_time) f.write("\r\n") f.write("end time :" + end_time) f.write("\r\n") f.write( "------------------------------------------------------\r\n") f.write("\r\n") time.sleep(20) GPIO.output(Pin_Relay, GPIO.HIGH) time.sleep(5) GPIO.output(Pin_Relay, GPIO.LOW)
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(): from pexpect_serial import SerialSpawn with serial.Serial('COM1', 38400, timeout=0) as ser: ss = SerialSpawn(ser) ss.sendline('start') ss.expect('done')
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")
class ConnectorPEexpect: PASSES = [] prompt = None serial = None child = None runit = False retries = 0 booting = False connected = False where = 'console' ssh = False def __init__(self, hostname, ip, port=''): self.username = USER self.ip = ip self.hostname = hostname self.port = port self.password = PASS # self.prompt = '' self.prompt = '#' self.passwordfile = './passwords.txt' self.retries = 0 self.runit = False def execute(self, cmd, echo=False): #v2 retour = 'aaa' timeout = 10 try: # try: # prompted = self.child.expect(['>', self.prompt], 1) # except pexpect.exceptions.TIMEOUT: # # if prompted != 0: # print("# Envoi d'une ligne vide pour forcer un prompt...") # # self.child.sendline('\r\n') # self.child.sendline('\r') print() print('# Execution de: ') if len(cmd) > 1: print("\n".join(cmd)) else: print(cmd[0]) if re.match("configure terminal", cmd[0]) is None: self.child.sendline(str(cmd[0])) # self.child.write(cmd[0]+'\r\n') # self.child.write(cmd[0]+'\n') if cmd[0] == 'exit': retour = '' # self.child.expect(self.prompt) # self.child.expect('available', timeout) # self.child.close() elif cmd[0] == 'reload': self.runit = False i = self.child.expect(['confirm', 'modif'], timeout) if i == 0: self.child.sendline('') # self.child.write('\r\n') if i == 1: self.child.sendline('yes') # self.child.write('yes\n') self.child.expect(['confirm'], timeout) self.child.sendline('') # self.child.write('\r\n') lastindexprinted = 0 # while retour != '': # while not self.runit: # try: self.booting = True if self.login(): self.runit = True self.booting = False retour = '' else: retour = 'disconnected' # except Exception as e: # print('# *** Exception recue lors execution reload:' + str(e)) # retour = 'disconnected' # return retour # if retour != 'disconnected': # retour = '' elif re.match("delete", cmd[0]) is not None: try: # self.child.expect(self.prompt, 300) # retour = '' # # retour = self.child.before.decode("utf-8") self.child.expect(["confirm", "filename"], 120) retour = self.child.before.decode("utf-8") # print(retour) # # if i == 0 or i == 1: # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) self.child.sendline('') # self.child.sendline('\r') # # self.child.sendline("") # # self.child.write('\r\n') self.child.expect(["filename", "confirm"], 120) retour = self.child.before.decode("utf-8") # print(retour) # # if i == 0 or i == 1: # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) # self.child.sendline('\r') self.child.sendline('') # else: self.child.expect(self.prompt, 120) retour = self.child.before.decode("utf-8") # print(retour) # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) if echo: print(retour) if retour.find('Error') > 0: print("# *** Erreur recue lors de la supression: ") if retour.find('Warning') > 0: # retour += self.child.before.decode("utf-8") print( "# ** Avertissement recue lors de la supression: " ) else: retour = '' else: retour = '' # print(retour) # elif i == 2 or i == 3: # self.child.sendline('\r') # # self.child.write('\r\n') retour = '' except Exception as e: print('# *** Exception recue lors execution delete:' + str(e)) retour = '' elif re.match("copy", cmd[0]) is not None: try: timeoutdownload = 300 while True: # i = self.child.expect(["\?", self.prompt, "already", "confirm", "Address", "Destination", pexpect.exceptions.TIMEOUT], timeout=timeoutdownload) i = self.child.expect([ self.prompt, "already", "confirm", "Address", "filename", pexpect.exceptions.TIMEOUT, '!' ], timeoutdownload) if i == 6: sys.stdout.write('!') else: retour = self.child.before.decode("utf-8") # print(retour) # i = self.child.expect(['remote host', 'Destination', self.prompt], timeout) # print("# i: " + str(i)) # print("# i=" + str(i)) # print("# prompt=" + self.prompt) # if i == 0: # retour = self.child.before.decode("utf-8") # if echo: # print(retour) # # self.child.sendline('') # # self.child.write('\r\n') # el if i == 0: if retour.find('Error') > 0: print( "# *** Erreur recue lors de la copie: " ) print(retour) if retour.find('Warning') > 0: # retour += self.child.before.decode("utf-8") print( "# ** Avertissement recue lors de la copie: " ) print(retour) # else: # retour = '' # else: # retour = '' if retour.find('bytes copied') > 0: print("# Operation complete") retour = '' if echo: print(retour) break elif i == 1: # print("# * Fichier deja present sur l'equipement: envoi de CTRL+c pour annuler cet operation") # # self.child.sendcontrol('c') # # self.child.send(chr(3)) # # self.child.sendline('') # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) print( "# Fichier present: ecriture (overwrite)") if echo: print(retour) # self.child.sendline('\003') self.child.sendline('') # retour = '' # break elif i == 2 or i == 3 or i == 4: # # self.child.sendline('') # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) if echo: print(retour) if i == 4: # self.child.sendline('\r\n') self.child.sendline('') else: # self.child.sendline('\r\n') self.child.sendline('') elif i == 5: print( "# * Temps d'attente expire pour la terminaison de la copie: le programme va continuer l'attente pour " + str(timeoutdownload) + " secondes supplementaires") # # continue naturally... # retour = self.child.before.decode("utf-8") # retour += self.child.after.decode("utf-8") # print(retour) except Exception as e: print('# *** Exception recue lors execution copy:' + str(e)) retour = "Error: " + str(e) elif re.match("configure terminal", cmd[0]) is not None: try: for command in cmd: self.child.sendline(command) # self.child.write(command+'\n') self.child.expect(self.prompt, timeout) retour = self.child.before.decode("utf-8") if echo: print( "# Affichage du retour de l'execution configure terminal sur l'equipement:" ) print("# ".join(retour)) print() except Exception as e: print( '# Exception recue lors execution configure terminal:' + str(e)) # print("# ".join(retour)) print() elif re.match("show", cmd[0]) is not None: try: # i = self.child.expect(self.prompt, 30) # print("# *** 'before':" + self.child.before.decode('UTF-8')) # print("# *** 'after':" + self.child.after.decode('UTF-8')) i = self.child.expect(self.prompt, 60) # self.child.sendeof() if i != 0: print( "# *** Erreur de communication resultante en executant: " + cmd[0]) print("# *** 'before':" + self.child.before.decode('UTF-8')) print("# *** 'after':" + self.child.after.decode('UTF-8')) else: if echo: print("# Commande executee") print(self.child.before.decode('UTF-8')) print(self.child.after.decode('UTF-8')) retour = self.child.before.decode('UTF-8') # retour += self.child.after.decode('UTF-8') except (pexpect.EOF, pexpect.TIMEOUT) as e: # if self.child.eof(): # print("# *** Prompt non recu lors de l'execution de la commande (EOF): " + cmd[0]) # else: # print("# *** Prompt non recu lors de l'execution de la commande (TIMEOUT): " + cmd[0]) print( "# *** Prompt non recu lors de l'execution de la commande: " + cmd[0]) if echo: print("# *** 'before':" + self.child.before.decode('UTF-8')) print("# *** 'after':" + self.child.after.decode('UTF-8')) print("# *** Details de l'exception recue: " + str(e)) elif re.match("terminal length 0", cmd[0]) is not None: try: # i = self.child.expect(self.prompt, 30) # print("# *** 'before':" + self.child.before.decode('UTF-8')) # print("# *** 'after':" + self.child.after.decode('UTF-8')) i = self.child.expect(self.prompt, 30) # self.child.sendeof() # time.sleep(1) if i != 0: print( "# *** Erreur de communication resultante en executant: " + cmd[0]) print("# *** 'before':" + self.child.before.decode('UTF-8')) print("# *** 'after':" + self.child.after.decode('UTF-8')) else: if echo: print("# Commande executee") print(self.child.before.decode('UTF-8')) print(self.child.after.decode('UTF-8')) retour = self.child.before.decode('UTF-8') # retour += self.child.after.decode('UTF-8') except (pexpect.EOF, pexpect.TIMEOUT) as e: # if self.child.eof(): # print("# *** Prompt non recu lors de l'execution de la commande (EOF): " + cmd[0]) # else: print( "# *** Prompt non recu lors de l'execution de la commande: " + cmd[0]) if echo: print("# *** 'before':" + self.child.before.decode('UTF-8')) print("# *** 'after':" + self.child.after.decode('UTF-8')) print("# *** Details de l'exception recue: " + str(e)) else: # print("# *** 'before':" + self.child.before.decode('UTF-8')) # print("# *** 'after':" + self.child.after.decode('UTF-8')) self.child.expect(self.prompt, 300) retour = self.child.before.decode("utf-8") if echo: print( "# Affichage du retour de l'execution par l'equipement:" ) # print("# ".join(retour)) print("# *** 'before':" + self.child.before.decode('UTF-8')) print("# *** 'after':" + self.child.after.decode('UTF-8')) # print(retour) # print() # if retour.find('L2') > 0: # print("# *** L'interface semble etre layer 2: ") # print(retour) # except Exception as e: except Exception as e: print('# *** Exception recue en executant:' + cmd[0]) print("# Details de l'exception:" + str(e)) return retour def asktocontinue(self, question): retour = input("\n" + question + "\n(oui/non): ") if retour.lower() == 'oui' or re.match(r'o', retour.lower()): return True else: return False def reconnect(self, where='console', echo=True): self.connected = False self.booting = True return self.connect(where, echo) def connect(self, where='console', echo=False, test=False): retour = False self.retries = 0 try: if where == 'serie': print('# * Connexion par SERIE vers:' + self.hostname + ' ' + self.ip + ' ' + self.port) # retour = self.ConnectSerial(test, echo) retour = self.ConnectSerial(echo, test) else: if not self.ssh: print('# * Connexion par TELNET vers:' + self.hostname + ' ' + self.ip + ' ' + self.port) retour = self.ConnectTelnet(where, echo) if not retour: print('# * Connexion par SSH vers:' + self.hostname + ' ' + self.ip + ' ' + self.username) retour = self.ConnectSsh(where, echo) if retour: self.ssh = True except Exception as e: print('# *** Exception recue:' + str(e)) try: if where != 'console' and where != 'serie': print('# * Connexion par SSH vers:' + self.hostname + ' ' + self.ip + ' ' + self.username) retour = self.ConnectSsh(where, True) except Exception as e: print('# *** Exception recue:' + str(e)) print('# *** Verifier ' + self.ip + ': Impossible de se connecter avec cet equipement') if not test: prompted = self.prompt.strip('#') if prompted == self.hostname: print("# * Le prompt obtenu est identique au nom d'hote") retour = True # retour = self.asktocontinue("# * Le prompt obtenu est identique au nom d'hote: desirez-vous poursuivre ?") else: print( "# *** Le prompt obtenu n'est pas identique au nom d'hote") retour = self.asktocontinue("# Desirez-vous poursuivre ?") if retour: self.where = where # self.getprompt() # self.execute(['terminal length 0'], echo) # i = self.child.expect(self.prompt, 30) # self.execute(['terminal monitor']) return retour def ConnectSerial(self, echo=False, test=False): #LINUX: chmod 666 /dev/ttyUSB0 self.retries = 0 try: # self.serial = serial.Serial(self.ip, int(self.port)) self.serial = serial.Serial(port=self.ip, baudrate=self.port, parity="N", stopbits=1, bytesize=8, timeout=3) # self.child = SerialSpawn(self.serial, encoding='utf-8') self.child = SerialSpawn(self.serial) if self.serial.isOpen(): print("# * Port console ouvert") # self.serial.write('\n') # self.child.sendline('') else: print("# *** Port console pas ouvert") # self.child.sendline('\r\n') # self.child.sendline('') # self.child.sendline('exit') if test: return True else: return self.login(echo) except Exception as e: print('# *** Exception recue par la connexion serie:' + str(e)) return False def ConnectTelnet(self, where='reseau', echo=False): self.retries = 0 try: # self.child = pexpect.spawn('telnet ' + self.ip + ' | tee -a ' + self.logfile) if where == 'console': self.child = pexpect.spawn('telnet ' + self.ip + ' ' + self.port, echo=False) else: self.child = pexpect.spawn('telnet ' + self.ip, echo=False) return self.login(echo) except Exception as e: print('# *** Exception recue par la connexion telnet:' + str(e)) return False # @property def ConnectSsh(self, where='reseau', echo=False): self.retries = 0 try: if where == 'console': self.child = pexpect.spawn('ssh ' + self.ip + ' -l ' + self.username + ' -p ' + self.port, echo=False) else: self.child = pexpect.spawn('ssh ' + self.ip + ' -l ' + self.username, echo=False) return self.login(echo) except Exception as e: print('# *** Exception recue par la connexion ssh:' + str(e)) return False def getprompt(self): self.prompt = self.child.before.decode('utf-8').rsplit( "\n")[-1:][0] + '#' self.prompt = self.prompt.replace('\r', '') self.prompt = self.prompt.replace('\n', '') prompted = self.prompt.strip('#') print('# * Prompt: ' + prompted) print('# * Hostname: ' + self.hostname) def login(self, echo=False): self.runit = False lastindexprinted = 0 print("# Login:"******"# Envoi d'une ligne vide pour forcer un prompt...") # self.child.sendline('\r') self.child.write('\r\n') # self.child.sendline('') try: gotdecompress = False while not self.runit: # i = self.child.expect(['[uU]sername:', '[lL]ogin:', '[pP]assword:', '>', '#', pexpect.exceptions.TIMEOUT, "initial configuration dialog?", "RETURN", pexpect.exceptions.EOF]) i = None tmpprompt1 = None tmpprompt2 = None if self.booting: tmpprompt1 = self.prompt.strip('#') + '>' tmpprompt2 = self.prompt else: tmpprompt1 = '>' tmpprompt2 = '#' print("# En attente du prompt: " + tmpprompt1 + " ou " + tmpprompt2 + " ou " + "'[uU]sername:' ou '[lL]ogin:' ou '[pP]assword:'") # print("# Envoi d'une ligne vide pour forcer un prompt...") # self.child.sendline('\r\n') # # self.child.sendline('\r\n') i = self.child.expect([ r'[uU]sername:', r'[lL]ogin:', r'[pP]assword:', tmpprompt1, tmpprompt2, pexpect.exceptions.TIMEOUT, "initial configuration dialog?", pexpect.exceptions.EOF, "RETURN" ], 30) #, '\r']) if i == 0: print('# Username prompt recu') self.child.sendline(self.username) # self.child.write(self.username+'\n') # self.runit = self.login() elif i == 1: print('# Login prompt recu') self.child.sendline(self.username) # self.child.write(self.username+'\n') # self.runit = self.login() elif i == 2: # self.child.expect('Password:'******'# Password prompt recu') print('# Envoi de:' + self.password) self.child.sendline(self.password) # self.child.write(self.password+'\n') # self.runit = self.login() elif i == 3: print('# > prompt recu') self.runit = self.enable(False) if self.runit == True: self.connected = True # self.prompt = self.child.before.decode('utf-8').rsplit("\r\n")[-1:][0] + '#' if not self.booting: self.getprompt() # self.runit = True elif i == 4: # print("# * Match #") # print(self.child.before.decode('utf-8')) # if re.match(r'.*decompressing', str(self.child.before.decode('utf-8'))) is not None: # if re.match("Self decompressing", self.child.before.decode('utf-8')): # if re.search("Booting", self.child.before.decode('utf-8'), re.MULTILINE) is not None: # # if not gotdecompress: # print("# Decompression de l'image, en demarrage....") # gotdecompress = True # else: # sys.stdout.write('.') # else: # # if re.match('.*#', self.child.after.decode("utf-8")) is None: # # # if re.match('.*##', self.child.before.decode("utf-8")) is not None: print('# # prompt recu') # self.prompt = self.child.before.decode('utf-8').rsplit("\r\n")[-1:][0] + '# if not self.booting: self.getprompt() self.runit = True # else: # sys.stdout.write('.') elif i == 5: #TIMETOUT print( "# * Temps d'attente expire: attente supplementaire..." ) # print("# Envoi d'une ligne vide pour forcer un prompt...") # self.child.sendline('\r\n') # self.child.sendline('\r') retour = self.child.before.decode("utf-8").split('\n') print("\n".join(retour[lastindexprinted:-1])) lastindexprinted = len(retour) print('# * Timeout recu sans prompt') self.retries += 1 if self.retries > 10: print( "# *** Apres quelques tentative d'obtenir le prompt" ) decision = input( "# Voulez-vous poursuivre la tentative de connexion ?\n(oui/non): " ) if decision.lower() != 'oui' or re.match( r'^o', decision.lower()) is not None: break else: self.retries = 0 elif i == 6: #INITIAL CONFIGURATION DIALOG print("# Recu initial configuration dialog: reponse no") self.child.sendline("no") # self.child.write('no\n') elif i == 8: print("# Envoi d'un retour de ligne car recu 'RETURN'") # self.child.sendline('\r') self.child.write('\r\n') elif i == 7: # TIMER = 10 print( "# *** Reception de EOF: deconnection probable avec l'equipement en redemarrage" ) break # elif i == 9: # print("# Netoyage ligne vide envoyee...") # print('# Envoi de ligne vide pour obtenir le prompt') # print("# En attente " + str(TIMER) + " secondes avant de tenter d'obtenir le prompt a nouveau") # time.sleep(TIMER) # # self.retries += 1 # if self.retries < 100: # print('# Envoi de ligne/retour') # # self.child.sendline('\r\n') # self.child.sendline('') # # self.runit = self.login() # else: # print("# *** Apres quelques tentative d'obtenir le prompt") # decision = input("Voulez-vous poursuivre la tentative de connexion ?\n(oui/non): ") # if decision.lower() != 'oui' or decision.lower().find(r'^o') < 1: # # raise ValueError('# Impossible de se connecter: pas de prompt') # break # else: # self.retries = 0 if echo: print("# Before:" + self.child.before.decode('UTF-8')) print("# After :" + self.child.after.decode('UTF-8')) except Exception as err: print( '# *** Exception recue: Impossible de se connecter par la methode login' ) print(str(err)) # self.prompt = '#' # self.child.sendline('terminal length 0') # # self.child.expect(self.prompt) # self.child.expect('#') # print(str(self.child.before)) if self.booting: print("# Apres redemarrage:") print(self.child.before.decode('UTF-8')) print(self.child.after.decode('UTF-8')) # self.getprompt() self.execute(['terminal length 0'], echo) return self.runit def enable(self, echo=False): print('# Niveau enable est requis pour continuer les travaux') print('# Verification du fichier de mot de passe:' + self.passwordfile) if path.exists(self.passwordfile): print('# Fichier de mots de passe present') if self.pass_file_accessible_read(self.passwordfile): print('# Fichier accessible en lecture') self.PASSES = self.pass_file_read(self.passwordfile) else: print('# *** Fichier inaccessible en lecture') else: print( "# *** Fichier de mot de passe introuvable: niveau insuffisant pour " ) print('# *** poursuivre les travaux sur cet equipement') # exit(0) print( "# Ajout du username comme enable password, insertion dans la liste des mots de passe" ) self.PASSES.append(self.username) print(self.PASSES) if self.booting: self.child.sendline('') # self.child.sendline('enable') enabled = False # for password in range(len(self.PASSES)): j = 0 passlen = len(self.PASSES) # while (not enabled) and (j<passlen): while j < passlen: if echo: print("# Before:" + self.child.before.decode('UTF-8')) print("# After :" + self.child.after.decode('UTF-8')) i = self.child.expect( [r'[pP]assword:', '#', '>', pexpect.exceptions.TIMEOUT]) if i == 0: mdp = self.PASSES[j] mdp = mdp.replace('\n', '') mdp = mdp.replace('\r', '') print('# Envoi du mot de passe:' + mdp) self.child.sendline(mdp) # self.child.write(self.PASSES[j]+'\n') j += 1 # print("# Attente d'une seconde avant de lire les donnees en retour") # time.sleep(3) elif i == 1: print('# Niveau atteind pour poursuivre les travaux') enabled = True break elif i == 2: if j == 0: print( "# Niveau insufissant, envoi de la commande 'enable' pour essayer les mots de passe connus" ) else: print( '# Niveau insufissant, relance de enable pour essayer les mots de passe restants' ) self.child.sendline('enable') else: print('# Autre resultat recu: timeout') print("Child: " + str(self.child)) print("Child before: " + str(self.child.before)) print("Child after: " + str(self.child.after)) self.child.sendline('') # self.child.write('\r\n') if not enabled: print("# *** Tous les mots de passe du fichier sont envoyes") print( '# *** Niveau insuffisant pour poursuivre les travaux sur cet equipement' ) # exit(0) return enabled def pass_file_accessible_read(self, file): return os.access(file, os.R_OK) def pass_file_read(self, file): PASSES = [] with open(file, "r") as read_file: PASSES = read_file.readlines() read_file.close() for i in range(len(PASSES)): apass = PASSES[i].replace('\r', '') PASSES[i] = apass.replace('\n', '') # print(PASSES) return PASSES def RunCmd(self, cmd): self.child.sendline(cmd) # self.child.write(cmd+'\n') self.child.expect('#') return (self.child, self.child.before) def TftpUpload(self, host2, file): cmdstring = 'copy tftp://' + host2 + "/" + file + ' flash:' try: self.child.sendline(cmdstring) # self.child.write(cmdstring+'\n') print('# En attente de retour de la commande:' + cmdstring) self.child.expect('\?') print('# Envoi de la confirmation du fichier:' + file) self.child.sendline(file) # self.child.write(file+'\n') print('# En attente du prompt') print('# Prompt attendu:') print(str(self.prompt)) # self.child.expect('#') i = self.child.expect([self.prompt, '[confirm]']) if i == 1: # self.child.write('y\n') self.child.sendline('y') self.child.expect(self.prompt) return (True, self.child, self.child.before) except Exception as e: print( '# *** Verifier la connexion avec le service: impossible de terminer cette tache' ) print('# *** Exception:' + str(e)) print('# *** Recu:') print("# ".join(self.child.before)) print() return (False, self.child, 'Erreur produite lors de la communication avec le service') def FtpUpload(self, host2, file, username, password): cmdstring = 'copy ftp://' + username + ":" + password + "@" + host2 + "/" + file + ' flash:' try: self.child.sendline(cmdstring) # self.child.write(cmdstring+'\n') print('# En attente de retour de la commande:' + cmdstring) self.child.expect('\?') print('# Envoi de la confirmation du fichier:' + file) self.child.sendline(file) # self.child.write(file+'\n') print('# En attente du prompt') # self.child.expect('#') i = self.child.expect([self.prompt, '[confirm]']) if i == 1: self.child.sendline('y') # self.child.write('y\n') self.child.expect(self.prompt) return (True, self.child, self.child.before) except Exception as e: print( '# ** Verifier la connexion avec le service: impossible de terminer cette tache' ) print('# ** Exception:' + str(e)) print('# ** Recu:') print("# ".join(self.child.before)) print() return (False, self.child, 'Erreur produite lors de la communication avec le service')
#!/usr/bin/python import serial from pexpect_serial import SerialSpawn ser = serial.Serial('/dev/ttyS0') ss = SerialSpawn(ser) ss.sendline('start') ss.expect('done') """ import serial ser = serial.Serial() ser.boudrate = 115200 ser.port = '/dev/ttyS0' ser Serial<id=0xa81c10, open=False>(port='/dev/ttyS0', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) ser.open() ser.close() """ """ import sys from pexpect import pxssh import getpass from ConfigParser import SafeConfigParser #parser = SafeConfigParser() #parser.read('../conf/conf.cnf') try: s = pxssh.pxssh() parser = SafeConfigParser() parser.read('/home/testuser/sachin/sky_auto/conf/conf.cnf') hostname = parser.get('config', 'hostname') #raw_input('hostname: ')