Пример #1
0
    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
Пример #2
0
    def __initserial__(self, com_port, speed, user, pwd, prompt):
        m = re.match('COM([0-9]+)', com_port)

        if m and settings.host_os == 'linux':
            com_num = m.group(1)
            com_port = '/dev/ttyS' + com_num

        self.__ui_str = 'console ' + com_port + ' baud rate ' + str(speed)
        UI.log('ACTION', 'Initializing ' + self.__ui_str)

        try:
            ser = serial.Serial(com_port, speed, timeout=0.1)
            self.__dut = SerialSpawn(ser, timeout=10, encoding='utf-8')
        except Exception as e:
            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: Serial spawn session failed to initialize'
                )
                sys.stdout.write(
                    'Please check console login credentials, and verify the COM port is available.'
                )
                sys.stdout.write(e)

            UI.log(
                'CRITICAL ALERT', 'Serial spawn session failed to initialize',
                'Please check console login credentials, and verify the COM port is available.',
                str(e))

            return 'FAIL'

        self.__prompt = prompt
        return self.__login__(user, pwd)
Пример #3
0
    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()
Пример #4
0
    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()
Пример #5
0
    def connect(self):
        try:
            ser = serial.Serial(self._cfg['serial_port'])
        except serial.serialutil.SerialException:
            sys.exit()

        ser.baudrate = 115200
        ser.bytesize = 8
        ser.stopbits = 1
        ser.xonxoff = 0
        ser.rtscts = 0
        ser.timeout = 0

        self._ss = SerialSpawn(ser)

        return self
Пример #6
0
    def open(self) -> bool:
        """Open the serial port and initialise the pexpect_serial object.

        Args: None
        Returns: None
        """
        # open serial port
        try:
            logger.debug("Opening serial port...")
            self.ser.open()
        except serial.SerialException:
            logger.exception(f"Could not open serial port {self.ser.name}")
            return False
        # and init pexpect_serial object
        self.ss = SerialSpawn(self.ser)
        logger.debug("Serial port opened OK!")
        return True
Пример #7
0
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()
Пример #8
0
    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)))
Пример #9
0
 def __init__(self, serial, logfile=None):
     self.logfile = logfile
     self.serial = serial
     self.child = SerialSpawn(serial, logfile=logfile, maxread=1)
Пример #10
0
    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()
Пример #11
0
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)
Пример #12
0
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
Пример #13
0
 def _init(self):
     ser = serial.Serial(self.port, 115200, timeout=2)
     self.ss = SerialSpawn(ser, timeout=2)
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')
Пример #15
0
import sys
import time
import serial
import pexpect
from pexpect_serial import SerialSpawn

#serial_port = sys.argv[1]

conf_commands = ['\r','rancid\r','\r','enable\r\n','\r\n']

console = serial.Serial()
console.port = "/dev/ttyUSB0"
#console.port = serial_port
console.baudrate = 9600
console.parity = "N"
console.stopbits = 1
console.bytesize = 8
console.timeout = 1
console.dsrdtr = False
console.rtscts = False
console.xonxoff = False

console.open()
ss = SerialSpawn(console)
for i in conf_commands:
    ss.writelines(conf_commands)
#    time.sleep(1)
console.close()
#switch erased
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
Пример #17
0
def serial_spawn():
    with serial.Serial('/dev/ttyACM0', 115200, timeout=1) as ser:
        yield SerialSpawn(ser)
Пример #18
0
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")
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')
Пример #20
0
import sys
import time
import serial
import pexpect
from pexpect_serial import SerialSpawn

conf_commands = "output/customer-sw-1-24-Fa.expect"

console = serial.Serial()
console.port = "/dev/ttyUSB0"
#console.port = serial_port
console.baudrate = 9600
console.parity = "N"
console.stopbits = 1
console.bytesize = 8
console.timeout = 1
console.dsrdtr = False
console.rtscts = False
console.xonxoff = False

console.open()
ss = SerialSpawn(console)
f = open(conf_commands, 'r')
for i in f:
    ss.writelines(f)
    time.sleep(2)
f.close()
console.close()
#switch erased
Пример #21
0
 def respawn(self):
     self.child = SerialSpawn(self.serial, logfile=self.logfile, maxread=1)
Пример #22
0
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')
Пример #23
0
class UI():
    """Class Name: UI
  Purpose
    Provides DUT command line user interface and terminal output/logging features.
  """

    log_stream = sys.stdout
    log_terminal_output = True
    end_msg = True
    last_ui = ''
    test_result = 'CHECK'

    def __init__(self, credentials, platform):
        self.__platform = platform
        self.__dut = None
        self.__prompt = ''
        self.__type = credentials[0].lower()
        self.__last_buff = ''
        self.__out_even = True

        if not settings.glb.show_login:
            UI.log_terminal_output = False

        if self.__type == 'host':
            if platform == 'windows':
                self.__EOF = pexpect_for_winpexpect.EOF
                self.__TIMEOUT = pexpect_for_winpexpect.TIMEOUT
            else:
                self.__EOF = pexpect.EOF
                self.__TIMEOUT = pexpect.TIMEOUT

            return
        elif self.__type == 'snmp':
            self.__dut_ip = credentials[1]
            self.__snmp_ver = credentials[2]
            return
        elif self.__type == 'console':
            self.__EOF = pexpect.EOF
            self.__TIMEOUT = pexpect.TIMEOUT
            login_status = self.__initserial__(*credentials[1:])
        elif 'telnet' in self.__type or 'ssh' in self.__type:
            if settings.host_os == 'windows':
                self.__EOF = pexpect_for_winpexpect.EOF
                self.__TIMEOUT = pexpect_for_winpexpect.TIMEOUT
            else:
                self.__EOF = pexpect.EOF
                self.__TIMEOUT = pexpect.TIMEOUT

            if 'telnet' in self.__type:
                login_status = self.__inittelnet__(*credentials[1:])
            elif 'ssh' in self.__type:
                login_status = self.__initssh__(*credentials[1:])

        if login_status == 'PASS':
            if self.__platform == 'simba':
                self.send('terminal length 0\r')
                self.expect(self.__prompt)
                self.send('terminal width ' + str(settings.glb.log_width) +
                          '\r')
                self.expect(self.__prompt)

            self.__last_buff = self.getBuff()
            UI.log_terminal_output = True
            self.__init = True
            return self.__dut

        elif login_status == 'FAIL':
            self.__init = False
            self.__dut = None
            self.__prompt = ''
            self.__type = ''
            return self.__dut

    def __setas__(self, other):
        self.__type = other.__type
        self.__dut = other.__dut
        self.__prompt = other.__prompt
        self.__last_buff = other.__last_buff
        self.__EOF = other.__EOF
        self.__TIMEOUT = other.__TIMEOUT
        self.__init = other.__init

    def __initserial__(self, com_port, speed, user, pwd, prompt):
        m = re.match('COM([0-9]+)', com_port)

        if m and settings.host_os == 'linux':
            com_num = m.group(1)
            com_port = '/dev/ttyS' + com_num

        self.__ui_str = 'console ' + com_port + ' baud rate ' + str(speed)
        UI.log('ACTION', 'Initializing ' + self.__ui_str)

        try:
            ser = serial.Serial(com_port, speed, timeout=0.1)
            self.__dut = SerialSpawn(ser, timeout=10, encoding='utf-8')
        except Exception as e:
            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: Serial spawn session failed to initialize'
                )
                sys.stdout.write(
                    'Please check console login credentials, and verify the COM port is available.'
                )
                sys.stdout.write(e)

            UI.log(
                'CRITICAL ALERT', 'Serial spawn session failed to initialize',
                'Please check console login credentials, and verify the COM port is available.',
                str(e))

            return 'FAIL'

        self.__prompt = prompt
        return self.__login__(user, pwd)

    def __inittelnet__(self, ip, port, user, pwd, prompt):
        if port != '':
            self.__ui_str = 'Telnet ' + ip + ' on port ' + port
        else:
            self.__ui_str = 'Telnet ' + ip

        UI.log('ACTION', 'Initializing ' + self.__ui_str)

        try:
            if settings.host_os == 'windows':
                if port != '':
                    spw = winspawn('bin_win32/plink -telnet ' + ip + ' -P ' +
                                   port)
                else:
                    spw = winspawn('bin_win32/plink -telnet ' + ip)
                    #spw = winspawn('bin_win32/telnet_win.exe '+ip)

            else:
                spw = pexpect.spawn('telnet ' + ip + ' ' + port,
                                    encoding='utf-8')

        except Exception as e:
            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: Telnet spawn session failed to initialize'
                )
                sys.stdout.write(
                    'Please check Telnet login credentials, and verify the IP address is configured '
                    + 'properly.')

                sys.stdout.write(e)

            UI.log(
                'CRITICAL ALERT', 'Telnet spawn session failed to initialize',
                'Please check Telnet login credentials, and verify the IP address is configured properly.',
                str(e))

            return 'FAIL'

        self.__dut = spw
        self.__prompt = prompt
        return self.__login__(user, pwd)

    def __initssh__(self, ip, port, user, pwd, prompt):
        if port != '':
            self.__ui_str = 'SSH ' + user + '@' + ip + ' on port ' + port
        else:
            self.__ui_str = 'SSH ' + user + '@' + ip

        UI.log('ACTION', 'Initializing ' + self.__ui_str)

        try:
            if settings.host_os == 'windows':
                if port != '':
                    spw = winspawn('bin_win32/plink -ssh ' + user + '@' + ip +
                                   ' -P ' + port)
                else:
                    spw = winspawn('bin_win32/plink -ssh ' + user + '@' + ip)

            else:
                spw = pexpect.spawn(
                    'ssh ' + user + '@' + ip + ' -p ' + port +
                    ' -o StrictHostKeyChecking=no -o ServerAliveInterval=60',
                    encoding='utf-8')

        except Exception as e:
            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: SSH spawn session failed to initialize')
                sys.stdout.write(
                    'Please check SSH login credentials, and verify the IP address is configured '
                    + 'properly.')

                sys.stdout.write(e)

            UI.log(
                'CRITICAL ALERT', 'SSH spawn session failed to initialize',
                'Please check SSH login credentials, and verify the IP address is configured properly.',
                str(e))

            return 'FAIL'

        self.__dut = spw
        self.__prompt = prompt
        return self.__login__(user, pwd)

    def __login__(self, user, pwd):
        if 'ssh' in self.__type and settings.host_os == 'windows':
            return_char = '\n'
        else:
            return_char = '\r'

        if not settings.glb.show_login and user != '' and pwd != '':
            UI.log('Logging in with username/password: '******'/' + pwd)

        login_count = 0
        status = ''

        try:
            # if 'telnet' in self.__type:
            #   self.send('')
            # else:
            # self.send('\r')
            self.send('\r')

            while True:
                i = self.expect([
                    '(Username|Login|sonic login|bmc-oob. login: ).*',
                    '(?i)password.*', '(?i)note:', self.__prompt,
                    '(?i)permission denied', 'y/n'
                ],
                                timeout=10)
                if i == 3:
                    status = 'PASS'
                    break
                elif i == 0:
                    self.send(user + return_char)
                elif i == 1:
                    self.send(pwd + return_char)
                    login_count += 1
                elif i == 2:
                    if self.__type == 'console':
                        self.send('\r')
                elif i == 5:
                    self.send('y' + return_char)

                if login_count > 2:
                    if not settings.glb.print_to_stdout:
                        sys.stdout.write(
                            'CRITICAL ALERT: %s Login failed. Permission denied for username/password: %s/%s'
                            % (self.__type.capitalize(), user, pwd))

                    UI.log(
                        'CRITICAL ALERT',
                        '%s Login failed. Permission denied for username/password: %s/%s'
                        % (self.__type.capitalize(), user, pwd))

                    status = 'FAIL'
                    break

            if not settings.glb.show_login:
                UI.log('LOGIN SUCCESS', str(self) + ' is initialized.')

            if status == 'FAIL':
                self.__dut.close()

            return status

        except self.__EOF:
            UI.log_stream.write(self.getBuff())

            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: %s login failed; please check login credentials.'
                    % self.__type.capitalize())

            UI.log(
                'CRITICAL ALERT',
                '%s login failed; please check login credentials.' %
                self.__type.capitalize())

        except self.__TIMEOUT:
            UI.log_stream.write(self.getBuff())

            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: %s login timed out; please check login credentials.'
                    % self.__type.capitalize())

            UI.log(
                'CRITICAL ALERT',
                '%s login timed out; please check login credentials.' %
                self.__type.capitalize())

    def getOutEven(self):
        return self.__out_even

    def init(self):
        return self.__init

    def getPrompt(self):
        return self.__prompt

    def getEOF(self):
        return self.__EOF

    def getTIMEOUT(self):
        return self.__TIMEOUT

    def close(self, close_cmd='exit'):
        if self.__dut is None:
            return

        if not settings.glb.show_login:
            UI.log('LOGGING OUT', 'Closed ' + self.__ui_str)
            UI.log_terminal_output = False

        try:
            self.send(settings.glb.ctrl_c)
            self.expect(self.__prompt, writting=None)
            self.send(close_cmd + '\r')

            while True:
                i = self.expect([
                    self.__EOF, '(?i)(note:|login|exit session).*',
                    self.__prompt
                ],
                                writting=None)

                if i == 0 or i == 1:
                    break
                elif i == 2:
                    self.send(close_cmd + '\r')

        except:
            if self.__dut.isalive():
                self.__dut.terminate()

        if self.__dut != None:
            self.__dut.close()

        if UI.log_terminal_output:
            UI.log('Closed ' + self.__ui_str)

        self.__dut = None
        self.__type = None
        self.__init = False
        UI.log_terminal_output = True
        return None

    def spawn(self, *cmd):
        try:
            if settings.host_os == 'windows':
                self.__ui_str = 'Windows host CMD'
                self.__dut = winspawn(*cmd)
            elif settings.host_os == 'linux':
                self.__ui_str = 'Linux host Bash shell'
                self.__dut = pexpect.spawn(*cmd, encoding='utf-8')

            cmd = ''.join(*cmd)
            UI.log('ACTION', 'Executing command on ' + self.__ui_str,
                   'Command: ' + cmd)
            UI.logTitle('TERMINAL OUTPUT from ' + self.__ui_str)
            UI.last_ui = str(self)
            last_line = self.__last_buff.split('\n')[-1]
            UI.log_stream.write(last_line)

            if settings.glb.print_to_stdout:
                sys.stdout.write(last_line)

            UI.end_msg = False
        except Exception as e:
            if not settings.glb.print_to_stdout:
                sys.stdout.write(
                    'CRITICAL ALERT: Host spawn session failed to initialize')
                sys.stdout.write(str(e))

            UI.log('CRITICAL ALERT', 'Host spawn session failed to initialize',
                   str(e))
            self.__dut = None

    def send(self, *args):
        if self.__dut == None:
            return

        if (UI.end_msg or UI.last_ui != str(self)) and UI.log_terminal_output:
            UI.log_stream.write(settings.glb.change_line)
            UI.logTitle('TERMINAL OUTPUT from ' + self.__ui_str)
            UI.last_ui = str(self)
            last_line = self.__last_buff.split('\n')[-1]
            UI.log_stream.write(last_line)

            if settings.glb.print_to_stdout:
                sys.stdout.write(last_line)

        UI.end_msg = False
        return self.__dut.send(*args)

    def sendWithoutOutput(self, *args):
        if self.__dut == None:
            return
        else:
            return self.__dut.send(*args)

    def expect(self,
               *args,
               timeout=10,
               writting=True,
               before=True,
               after=True):
        self.__out_even = False
        expectError = False

        if self.__dut == None:
            return

        try:
            ret = self.__dut.expect(*args, timeout=timeout)
        except:
            expectError = True
            ret = 1
            pass

        if writting:
            buff = self.getBuff(before=before, after=after)
            if UI.log_terminal_output:
                UI.log_stream.write(buff)

                if settings.glb.print_to_stdout:
                    sys.stdout.write(buff)

            else:
                UI.end_msg = True

            if args[0][ret] == self.__EOF:
                UI.last_ui = ''
                self.__dut = None
                self.__last_buff = ''
            else:
                self.__last_buff = buff

        self.__out_even = True
        if expectError:
            return 100
        else:
            return ret

    def getBuff(self, before=True, after=True):
        if self.__dut == None:
            return ''

        ret_str = ''

        if 'str' in str(type(self.__dut.before)) and before:
            ret_str = self.__dut.before

        if 'str' in str(type(self.__dut.after)) and after:
            ret_str += self.__dut.after

        return ret_str

    def getLastBuff(self):
        return self.__last_buff

    def getBeforeBuff(self):
        if 'str' in str(type(self.__dut.before)):
            return self.__dut.before
        else:
            return "NULL"

    def getAfterBuff(self):
        if 'str' in str(type(self.__dut.after)):
            return self.__dut.after
        else:
            return "NULL"

    def sendCmd(self, cmd, prompt="", writting=True, timeout=10):
        if prompt == "":
            prompt = self.__prompt
        self.send(cmd + '\r')
        ret = self.expect(prompt, writting=writting, timeout=timeout)
        if ret == 0:
            return self.getOutputFromLastBuff(cmd, prompt=prompt)
        else:
            return ""

    def getOutputFromLastBuff(self, cmd, prompt=""):
        if prompt == "":
            prompt = self.__prompt
        relist = self.getBuff().splitlines()
        retstr = ""
        for line in relist:
            if not re.search('^\x1b]0;root.*', line):
                if cmd != line:
                    retstr += line + '\n'
        return retstr

    def snmpGet(self,
                oids,
                credentials='',
                port=161,
                engine=hlapi.SnmpEngine(),
                context=hlapi.ContextData()):
        target = self.__dut_ip

        if self.__snmp_ver.lower() == '2c':
            credentials = hlapi.CommunityData('public')

        handler = hlapi.getCmd(engine, credentials,
                               hlapi.UdpTransportTarget((target, port)),
                               context, *construct_object_types(oids))

        ret = fetch(handler, 1)[0]
        ret_list = []

        for key, value in ret.items():
            temp = key + ': ' + value
            ret_list.append(temp)

        UI.log('SNMP-GET', 'Remote IP: ' + self.__dut_ip, *ret_list)
        return ret

    def snmpSet(self,
                value_pairs,
                credentials='',
                port=161,
                engine=hlapi.SnmpEngine(),
                context=hlapi.ContextData()):
        target = self.__dut_ip

        if self.__snmp_ver.lower() == '2c':
            credentials = hlapi.CommunityData('private')

        handler = hlapi.setCmd(engine, credentials,
                               hlapi.UdpTransportTarget((target, port)),
                               context, *construct_value_pairs(value_pairs))

        ret = fetch(handler, 1)[0]
        ret_list = []

        for key, value in ret.items():
            temp = key + ': ' + value
            ret_list.append(temp)

        UI.log('SNMP-SET', 'Remote IP: ' + self.__dut_ip, *ret_list)
        return ret

    @classmethod
    def openLog(class_object, filename):
        UI.log_stream = open(filename, 'a')

    @classmethod
    def logTitle(class_object, title):
        if not UI.end_msg:
            UI.log_stream.write(settings.glb.change_line)

            if settings.glb.print_to_stdout:
                sys.stdout.write('\n')

        centered_title = '{:=^{w}}'.format(' ' + title + ' ',
                                           w=settings.glb.log_width)
        UI.log_stream.write(centered_title)

        if settings.glb.print_to_stdout:
            sys.stdout.write(centered_title)

        UI.log_stream.write(settings.glb.change_line)
        UI.end_msg = True

        if settings.glb.print_to_stdout:
            sys.stdout.write('\n\n')

        if title == 'PASS' and UI.test_result == 'CHECK':
            UI.test_result = 'PASS'
        elif title == 'FAIL':
            UI.test_result = 'FAIL'

    @classmethod
    def log(class_object, *msg):
        if not UI.end_msg:
            UI.log_stream.write(settings.glb.change_line)

            if settings.glb.print_to_stdout:
                sys.stdout.write('\n')

        if msg[0].isupper():
            title = msg[0]
            msg = msg[1:]
            UI.logTitle(title)
        else:
            divider = '=' * settings.glb.log_width
            UI.log_stream.write(divider)
            UI.log_stream.write(settings.glb.change_line)

            if settings.glb.print_to_stdout:
                sys.stdout.write(divider)
                sys.stdout.write('\n\n')

        first_word = msg[0].split(' ')[0]

        if re.match('(\.|:)', first_word[-1]):
            indent = ' ' * (len(first_word) + 1)
        else:
            indent = ''

        for m in msg:
            # Perform word wrap for each line of message.
            m.strip('\n')
            lines = ''
            word_list = str(m).split(' ')

            for w in word_list:
                last_line = (lines + w).split('\n')[-1]

                if len(last_line) > settings.glb.log_width:
                    lines += '\n' + indent + w + ' '
                else:
                    lines += w + ' '

            UI.log_stream.write(lines + '\n')

            if settings.glb.print_to_stdout:
                sys.stdout.write(lines + '\n')

        if settings.glb.print_to_stdout:
            sys.stdout.write('\n')

        UI.end_msg = True

    @classmethod
    def closeLog(class_object):
        UI.log_stream.write('\n\n')
        UI.log_stream.close()
        f = open(UI.log_stream.name, 'r')
        l_list = f.readlines()
        f.close()
        new_f = open(UI.log_stream.name, 'w')
        empty_line_count = 0

        for l in l_list:
            l = l.replace(']0;root@minipack:~', '')
            if re.search('^[\r\n]+$', l, re.M) or len(l) == 1:
                empty_line_count += 1
            else:
                if empty_line_count > 2:
                    new_f.write('\n')

                new_f.write(l)
                empty_line_count = 0

        new_f.close
Пример #24
0
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)
Пример #25
0
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
Пример #26
0
class PipeSerial:
    """The PipeSerial class."""

    __version__ = __version__

    def __init__(
        self,
        serialport: str,
        baudrate: int = 115200,
        bytesize: int = 8,
        parity: str = "N",
        stopbits: float = 1,
        rtscts: bool = False,
        xonxoff: bool = False,
        rts: typing.Optional[int] = None,
        dtr: typing.Optional[int] = None,
    ) -> None:
        """Initialise pyserial object and configure the serial port.

        Args:
            serialport: The serial port device to use, like "/dev/cuaU0"
            baudrate: The serial port speed, default: 115200
            bytesize: Serial port bytesize, one of {5 6 7 8}, default: 8
            parity: Serial port parity, one of {N E O S M}, default: N
            stopbits: Serial port stopbits, one of {1 1.5 2}, default: 1
            rtscts: Enable serial port RTS/CTS hardware flow control, default: False
            xonxoff: Enable serial port software flow control, default: False
            rts: Set initial RTS line state, one of {0, 1}, default: None
            dtr: Set initial DTR line state, one of {0, 1}, default: None

        Returns:
            Nothing
        """
        logger.debug(f"Configuring serial port {serialport} ...")
        self.ser = serial.serial_for_url(serialport, do_not_open=True)
        self.ser.baudrate = baudrate
        self.ser.bytesize = bytesize
        self.ser.parity = parity
        self.ser.stopbits = stopbits
        self.ser.rtscts = rtscts
        self.ser.xonxoff = xonxoff
        if rts is not None:
            self.ser.rts = rts
        if dtr is not None:
            self.ser.dtr = dtr

    def open(self) -> bool:
        """Open the serial port and initialise the pexpect_serial object.

        Args: None
        Returns: None
        """
        # open serial port
        try:
            logger.debug("Opening serial port...")
            self.ser.open()
        except serial.SerialException:
            logger.exception(f"Could not open serial port {self.ser.name}")
            return False
        # and init pexpect_serial object
        self.ss = SerialSpawn(self.ser)
        logger.debug("Serial port opened OK!")
        return True

    def run(
        self,
        payload: str,
        expect: typing.List[str],
        delay: float = 0.9,
        expectcount: int = 1,
        timeout: int = 30,
    ) -> typing.List[str]:
        """Send the payload to serial device.

        Args:
            payload: The payload to send to the serial device.
            expect: A list of regex to expect as the end of output.

        Returns:
            The output from the serial device as list of string, one for each line.
        """
        # send the input to serial, line by line, with \r\n newlines
        for line in payload.split("\n"):
            if not line:
                # skip empty lines
                continue
            logger.debug(f"Sending payload line: {line}")
            self.ss.send(line.strip() + "\r\n")
            time.sleep(delay)

        # Wait for some matching output
        output = b""
        logger.debug(
            f"Collecting output, looking for one of these regular expressions: {expect}"
        )
        logger.debug(f"Will stop collecting after {expectcount} matches")
        for i in range(1, expectcount + 1):
            match = self.ss.expect(expect, timeout=timeout)
            logger.debug(
                f"Found match: '{expect[match].strip()}' (match number {i} of {expectcount})"
            )
            # we want all the output, before and including the expected string
            output += self.ss.before + self.ss.after

        # decode, strip and return the lines of output
        logger.debug(
            f"Done! Returning {len(output)} bytes of output from serial device"
        )
        return [line.strip() for line in output.decode("LATIN1").split("\n")]

    def close(self) -> None:
        """Close the serial port."""
        logger.debug("Closing serial port...")
        self.ss.ser.close()
        logger.debug("Serial port closed")
 def _init(self):
     ser = serial.Serial(self.port, 115200, timeout=2)
     self.ss = SerialSpawn(ser, timeout=2)
Пример #28
0
            ss.expect('Password', 2)
            ss.sendline(password)

            if (is_loggedin(ss)):
                return True
        except:
            pass

    return False


c_pwr = power_ctl()
prev_state = "OK"
with serial.Serial('/dev/ttyS0', 9600, timeout=0) as ser:
    while (1):
        ss = SerialSpawn(ser)

        if (not try_login(ss, 'tryagain', 'tryagain')):
            # Either its stuck or not powered on

            print(
                "Computer is probably mad and it doesn't speak to me anymore")
            # Most probably it's a freeze since it was ok before
            if (prev_state == "OK"):
                print("Lets try to calm it down with a restart")
                c_pwr.restart()
                prev_state = "RESTART"
            else:
                print("Even restart didn't fix it, now it's electricity time")
                c_pwr.powerbutton()
                prev_state = "POWER"
Пример #29
0
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())
Пример #30
0
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))
Пример #31
0
#!/usr/bin/python3

import sys

# pip3 install pyserial
# sudo apt-get install python3-serial
import serial

# pip3 install pexpect-serial
from pexpect_serial import SerialSpawn
# If pexpect-serial is not available, use pexpect + picocom.

with serial.Serial('/dev/ttyACM0', baudrate = 115200, bytesize = 8, \
        parity = 'N', stopbits = 1) as ser:
    p = SerialSpawn(ser)
    p.logfile_read = sys.stdout.buffer
    p.expect('U-Boot ')
    p.expect('Hit any key to stop autoboot: ')
    p.send("s")
    p.expect('> ')
    p.logfile_read = None
    p.interact()  # press CTRL-] to contine python execution

# python3 -c "
# import pexpect, sys
# c = pexpect.spawn('$VPN_CMD')
# c.logfile_read = sys.stdout.buffer
# c.expect('Password:'******'$VPN_PASSWORD')
# c.interact()
# "
Пример #32
0
#!/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: ')