def _setupChild(self, masterfd, slavefd): """ Setup child process after fork() but before exec(). """ os.close(masterfd) if hasattr(termios, 'TIOCNOTTY'): try: fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) except OSError: pass else: try: fcntl.ioctl(fd, termios.TIOCNOTTY, '') except: pass os.close(fd) os.setsid() if hasattr(termios, 'TIOCSCTTY'): fcntl.ioctl(slavefd, termios.TIOCSCTTY, '') for fd in range(3): if fd != slavefd: os.close(fd) os.dup2(slavefd, 0) # stdin os.dup2(slavefd, 1) # stdout os.dup2(slavefd, 2) # stderr for fd in xrange(3, 256): try: os.close(fd) except: pass
def __init__(self, device, snaplen=64, promisc=1, to_ms=1000, activate=True, **kwargs): super(PcapPyLive, self).__init__() self._device = device self._promisc = promisc self._timeout = to_ms self._activate = activate self._rfmon = kwargs.get("rfmon", 0) self._buffer_size = kwargs.get("buffer_size", None) errbuf = create_string_buffer(PCAP_ERRBUF_SIZE) if self._activate and not self._rfmon and self._buffer_size is None: self._p = pcap_open_live(_to_bytes(device), snaplen, promisc, to_ms, c_char_p((addressof(errbuf)))) if not to_ms and (sys.platform.startswith("linux") or sys.platform == "darwin"): from fcntl import ioctl try: ioctl(self.fileno, BIOCIMMEDIATE, pack("I", 1)) except IOError: pass if not self._p: raise PcapPyException(errbuf.raw) else: self._p = pcap_create(_to_bytes(device), c_char_p((addressof(errbuf)))) if not self._p: raise PcapPyException(errbuf.raw) self.snaplen = snaplen self.promisc = self._promisc self.timeout = self._timeout if self._rfmon: self.rfmon = self._rfmon if self._buffer_size is not None: self.buffer_size = self._buffer_size if self._activate: self.activate()
def __init__(self, sensor_name, bus, addr=_DEFAULT_ADDRESS): '''Initializes the sensor with some default values. bus: The SMBus descriptor on which this sensor is attached. addr: The I2C bus address (default is 0x40). ''' SensorBase.__init__( self, sensor_name=sensor_name) self._ior = io.open('/dev/i2c-' + str(bus), 'rb', buffering=0) self._iow = io.open('/dev/i2c-' + str(bus), 'wb', buffering=0) fcntl.ioctl(self._ior, _I2C_SLAVE, addr) fcntl.ioctl(self._iow, _I2C_SLAVE, addr) self._resolution = RESOLUTION_12BITS self._onchip_heater = _DISABLE_ONCHIP_HEATER self._otp_reload = _DISABLE_OTP_RELOAD self._use_temperature = True self._reset() self._reconfigure()
def PPRELEASE(self): """ Releases the port. Releasing the port undoes the effect of claiming the port. It allows other device drivers to talk to their devices (assuming that there are any). """ fcntl.ioctl(self._fd, PPRELEASE)
def process_IAC(self, sock, cmd, option): """ Read in and parse IAC commands as passed by telnetlib. SB/SE commands are stored in sbdataq, and passed in w/ a command of SE. """ if cmd == DO: if option == TM: # timing mark - send WILL into outgoing stream os.write(self.remote, IAC + WILL + TM) else: pass elif cmd == IP: # interrupt process os.write(self.local, chr(ord('C') & 0x1F)) elif cmd == SB: pass elif cmd == SE: option = self.sbdataq[0] if option == NAWS: # negotiate window size. cols = ord(self.sbdataq[1]) rows = ord(self.sbdataq[2]) s = struct.pack('HHHH', rows, cols, 0, 0) fcntl.ioctl(self.local, termios.TIOCSWINSZ, s) elif cmd == DONT: pass else: pass
def setDTR(self, level=1): """Set terminal status line: Data Terminal Ready""" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
def set_i2c_address(self, addr): # set the I2C communications to the slave specified by the address # The commands for I2C dev using the ioctl functions are specified in # the i2c-dev.h file from i2c-tools I2C_SLAVE = 0x703 fcntl.ioctl(self.file_read, I2C_SLAVE, addr) fcntl.ioctl(self.file_write, I2C_SLAVE, addr)
def setBreak(self, level=1): """Set break: Controls TXD. When active, to transmitting is possible.""" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCSBRK) else: fcntl.ioctl(self.fd, TIOCCBRK)
def setRTS(self, level=1): """Set terminal status line: Request To Send""" if self.fd is None: raise portNotOpenError if level: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
def _freeLoops(self): # Try N times to free N devices; that's enough to handle # nested devices but won't get stuck in really sticky cases. for tries in range(self.loopManager.chunk): goAgain = False for n, minor in enumerate(self.loops): path = os.path.join(self.mountPoint, 'loop%d' % n) try: fcntl.ioctl(open(path), LOOP_CLR_FD) except IOError, err: if err.errno == errno.ENXIO: # No such device or address - OK continue elif err.errno == errno.EBUSY: # Device or resource busy - try again log.warning("Loop device %d is busy", n) goAgain = True continue else: # Something else log.exception("Error freeing loop device:") else: log.info("Freed loop device %d", n) if not goAgain: break
def __init__(self, iface=None, type=ETH_P_ALL, filter=None, nofilter=0): if iface is None: iface = conf.iface self.iface = iface self.ins = open_pcap(iface, 1600, 0, 100) try: ioctl(self.ins.fileno(), BIOCIMMEDIATE, struct.pack("I", 1)) except: pass if nofilter: if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap filter = "ether proto %i" % type else: filter = None else: if conf.except_filter: if filter: filter = "(%s) and not (%s)" % (filter, conf.except_filter) else: filter = "not (%s)" % conf.except_filter if type != ETH_P_ALL: # PF_PACKET stuff. Need to emulate this for pcap if filter: filter = "(ether proto %i) and (%s)" % (type, filter) else: filter = "ether proto %i" % type if filter: self.ins.setfilter(filter) self.outs = dnet.eth(iface)
def _doaead(self, op, src, aad, iv, tag=None): caead = CryptAEAD() caead.ses = self._ses caead.op = op caead.flags = CRD_F_IV_EXPLICIT caead.flags = 0 caead.len = len(src) s = array.array('B', src) caead.src = caead.dst = s.buffer_info()[0] caead.aadlen = len(aad) saad = array.array('B', aad) caead.aad = saad.buffer_info()[0] if self._maclen is None: raise ValueError('must have a tag length') if tag is None: tag = array.array('B', [0] * self._maclen) else: assert len(tag) == self._maclen, `len(tag), self._maclen` tag = array.array('B', tag) caead.tag = tag.buffer_info()[0] ivbuf = array.array('B', iv) caead.ivlen = len(iv) caead.iv = ivbuf.buffer_info()[0] ioctl(_cryptodev, CIOCCRYPTAEAD, str(caead)) s = s.tostring() return s, tag.tostring()
def _has_sudo(self, result): _master, slave = pty.openpty() os.setsid() fcntl.ioctl(slave, termios.TIOCSCTTY, 0) out, err, exit = run_command(['sudo', '-l', '-U', self.user[USER_NAME], 'sudo']) if exit == 0: debug("User %s is allowed to run sudo" % self.user[USER_NAME]) # sudo allows a wide range of configurations, such as controlling # which binaries the user can execute with sudo. # For now, we will just check whether the user is allowed to run # any command with sudo. out, err, exit = run_command(['sudo', '-l', '-U', self.user[USER_NAME]]) for line in out.split('\n'): if line and re.search("(ALL)", line): result.value = 1 debug("User %s can run any command with sudo" % result.value) return debug("User %s can only run some commands with sudo" % self.user[USER_NAME]) else: debug("User %s is not allowed to run sudo" % self.user[USER_NAME])
def _getdev(): fd = os.open('/dev/crypto', os.O_RDWR) buf = array.array('I', [0]) ioctl(fd, CRIOGET, buf, 1) os.close(fd) return buf[0]
def __init__(self, cipher=0, key=None, mac=0, mackey=None, crid=CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE): self._ses = None ses = SessionOp2() ses.cipher = cipher ses.mac = mac if key is not None: ses.keylen = len(key) k = array.array('B', key) ses.key = k.buffer_info()[0] else: self.key = None if mackey is not None: ses.mackeylen = len(mackey) mk = array.array('B', mackey) ses.mackey = mk.buffer_info()[0] self._maclen = 16 # parameterize? else: self._maclen = None if not cipher and not mac: raise ValueError('one of cipher or mac MUST be specified.') ses.crid = CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE #ses.crid = CRYPTOCAP_F_HARDWARE #ses.crid = CRYPTOCAP_F_SOFTWARE #ses.crid = 0 #print `ses` s = array.array('B', ses.pack_hdr()) #print `s` ioctl(_cryptodev, CIOCGSESSION2, s, 1) ses.unpack(s) self._ses = ses.ses
def attach(self, part_id, path): """ Attaches MicroSAN as Network Block Device """ # Open NBD device nbd_fd = os.open(path, os.O_RDWR) # Set kernel parameters for NBD sysfs_name = '/sys/block/%s/queue/max_sectors_kb' % os.path.basename(path) sysfs = os.open(sysfs_name, os.O_RDWR) os.write(sysfs, '8') os.close(sysfs) # Resolve partition ip address part_ipaddr = self.name_res(part_id)[1] # Get partition information part_info = self._query_part(part_ipaddr)[0] # Parse partition information part_data = uSanProto.Partitions.parse_root_info(part_info[0]) part_size = part_data[1] # Size of blocks (12 = 4KB block) block_size_power = 12 block_size = part_size >> block_size_power # Set block sizes on device ioc = fcntl.ioctl(nbd_fd, NBD_SET_BLKSIZE, long(1 << block_size_power)) if ioc < 0: raise IOError('nbd_fd cannot set NBD_SET_BLKSIZE') ioc = fcntl.ioctl(nbd_fd, NBD_SET_SIZE_BLOCKS, block_size) if ioc < 0: raise IOError('nbd_fd cannot set NBD_SET_SIZE_BLOCKS')
def open(self, device_id): """ Open the joystick device. The device_id is given by available_devices """ if self.opened: return raise Exception("A joystick is already opened") self.device_id = device_id self.jsfile = open("/dev/input/js{}".format(self.device_id), "r") fcntl.fcntl(self.jsfile.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) val = ctypes.c_int() if fcntl.ioctl(self.jsfile.fileno(), JSIOCGAXES, val) != 0: self.jsfile.close() raise Exception("Failed to read number of axes") self.axes = list(0 for i in range(val.value)) if fcntl.ioctl(self.jsfile.fileno(), JSIOCGBUTTONS, val) != 0: self.jsfile.close() raise Exception("Failed to read number of axes") self.buttons = list(0 for i in range(val.value)) self.__initvalues() self.opened = True print self.devices[device_id]
def fiemap(fd): """ Gets a map of file extents. """ count = 72 fiemap_cbuf = ffi.new( 'char[]', ffi.sizeof('struct fiemap') + count * ffi.sizeof('struct fiemap_extent')) fiemap_pybuf = ffi.buffer(fiemap_cbuf) fiemap_ptr = ffi.cast('struct fiemap*', fiemap_cbuf) assert ffi.sizeof(fiemap_cbuf) <= 4096 while True: fiemap_ptr.fm_length = lib.FIEMAP_MAX_OFFSET fiemap_ptr.fm_extent_count = count fcntl.ioctl(fd, lib.FS_IOC_FIEMAP, fiemap_pybuf) if fiemap_ptr.fm_mapped_extents == 0: break for i in xrange(fiemap_ptr.fm_mapped_extents): extent = fiemap_ptr.fm_extents[i] yield FiemapExtent( extent.fe_logical, extent.fe_physical, extent.fe_length, extent.fe_flags) fiemap_ptr.fm_start = extent.fe_logical + extent.fe_length
def query_nat(self, family, proto, src_ip, src_port, dst_ip, dst_port): [proto, family, src_port, dst_port] = [ int(v) for v in [proto, family, src_port, dst_port]] packed_src_ip = socket.inet_pton(family, src_ip) packed_dst_ip = socket.inet_pton(family, dst_ip) assert len(packed_src_ip) == len(packed_dst_ip) length = len(packed_src_ip) pnl = self.pfioc_natlook() pnl.proto = proto pnl.direction = self.PF_OUT pnl.af = family memmove(addressof(pnl.saddr), packed_src_ip, length) memmove(addressof(pnl.daddr), packed_dst_ip, length) self._add_natlook_ports(pnl, src_port, dst_port) ioctl(pf_get_dev(), self.DIOCNATLOOK, (c_char * sizeof(pnl)).from_address(addressof(pnl))) ip = socket.inet_ntop( pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw) port = socket.ntohs(self._get_natlook_port(pnl.rdxport)) return (ip, port)
def resize(self): logger = logging.getLogger() logger.debug('send TIOCSWINSZ: %dx%d', self._term.width, self._term.height) fcntl.ioctl(self.master_fd, termios.TIOCSWINSZ, struct.pack('HHHH', self._term.height, self._term.width, 0, 0))
def connectionMade(self): self._tapBuff = "" self._mbDataToWrite = "" self._mbBuffLock = threading.Lock() self._tapBuffLock = threading.Lock() self._tapLock = threading.Lock() self._mbParseLock = threading.Lock() self._decoder = modbus.ModbusDecoder() print "sending login" self.sendMessage("login secret") #print "starting command thread" #self._commandThread = Thread(target = self.commandLoop, args = []) #self._commandThread.start() print "starting query thread" self._queryThread = Thread(target = self.pollLoop) # adjust accordingly self._queryThread.start() print "opening tap" self._tap = open('/dev/net/tun', 'w+b') self._ifr = struct.pack('16sH', 'tap1', IFF_TAP | IFF_NO_PI) fcntl.ioctl(self._tap, TUNSETIFF, self._ifr) # need to make the tap device nonblocking tapfd = self._tap.fileno() tapfl = fcntl.fcntl(tapfd, fcntl.F_GETFL) fcntl.fcntl(tapfd, fcntl.F_SETFL, tapfl | os.O_NONBLOCK) # Optionally, we want it be accessed by the normal user. fcntl.ioctl(self._tap, TUNSETOWNER, 1000) # subprocess.check_call('ifconfig tun0 192.168.7.1 pointopoint 192.168.7.2 up', subprocess.check_call('ifconfig tap1 192.168.7.2 netmask 255.255.255.0', shell=True) print "starting tap thread" self._tapThread = Thread(target = self.handle_tap, args = []) self._tapThread.start()
def destroyDevice (self): """ "Destroy" the device previously created on a the uinput node. NB. I have no idea if this is at all necessary... """ UI_DEV_DESTROY = 0x5502 fcntl.ioctl(self.fd, UI_DEV_DESTROY)
def __init__(self, nonblock=False, cloexec=True, mtu=150): self.fd = socket.socket(PF_SYSTEM, socket.SOCK_DGRAM, SYSPROTO_CONTROL) info = ctl_info(0, UTUN_CONTROL_NAME) fcntl.ioctl(self.fd, CTLIOCGINFO, info) self.fd.connect((info.ctl_id, 0)) self.iface = self.fd.getsockopt(SYSPROTO_CONTROL, UTUN_OPT_IFNAME, 256)[:-1] if nonblock: fcntl.fcntl(self.fd, fcntl.F_SETFL, os.O_NONBLOCK) if cloexec: fcntl.fcntl(self.fd, fcntl.F_SETFD, fcntl.FD_CLOEXEC) self.mtu = mtu # From ifconfig.8: ## Basic IPv6 node operation requires a link-local address on each ## interface configured for IPv6. Normally, such an address is ## automatically configured by the kernel on each interface added to ## the system; this behaviour may be disabled by setting the sysctl MIB ## variable net.inet6.ip6.auto_linklocal to 0. ## If you delete such an address using ifconfig, the kernel may act very odd. Do this at your own risk. # force generation of link-local address and routes subprocess.Popen(['ifconfig', self.iface, 'inet6', 'fe80::1/64', 'mtu', str(self.mtu)]).wait() subprocess.Popen(['ifconfig', self.iface, 'inet6', 'delete', 'fe80::1']).wait() time.sleep(.5) subprocess.Popen(['route', '-q', 'delete', '-inet6', '-net', 'fe80::%%%s/64' % self.iface]).wait() subprocess.Popen(['route', '-q', 'add', '-inet6', '-net', 'fe80::%%%s/64' % self.iface, '-interface', self.iface]).wait() time.sleep(.5) subprocess.Popen(['ifconfig', self.iface, 'inet6', 'fe80::1/64', 'mtu', str(self.mtu)]).wait() subprocess.Popen(['ifconfig', self.iface, 'inet6', 'delete', 'fe80::1']).wait() time.sleep(.5) subprocess.Popen(['route', '-q', 'delete', '-inet6', '-net', 'fe80::%%%s/64' % self.iface]).wait() subprocess.Popen(['route', '-q', 'add', '-inet6', '-net', 'fe80::%%%s/64' % self.iface, '-interface', self.iface]).wait() time.sleep(.5) self.fileno = self.fd.fileno
def transaction(self, bytes_to_send): """Sends bytes via the SPI bus. :param bytes_to_send: The bytes to send on the SPI device. :type bytes_to_send: bytes :returns: bytes -- returned bytes from SPI device :raises: InitError """ bytes_to_send = _pybytes(bytes_to_send) # make some buffer space to store reading/writing wbuffer = ctypes.create_string_buffer(bytes_to_send, len(bytes_to_send)) rbuffer = ctypes.create_string_buffer(len(bytes_to_send)) # create the spi transfer struct transfer = spi_ioc_transfer( tx_buf=ctypes.addressof(wbuffer), rx_buf=ctypes.addressof(rbuffer), len=ctypes.sizeof(wbuffer)) if self.spi_transaction_callback is not None: self.spi_transaction_callback(bytes_to_send) # send the spi command ioctl(self.fd, SPI_IOC_MESSAGE(1), transfer) return _pyord(ctypes.string_at(rbuffer, ctypes.sizeof(rbuffer)))
def _set_rs485_mode(self, rs485_settings): buf = array.array('i', [0] * 8) # flags, delaytx, delayrx, padding try: fcntl.ioctl(self.fd, TIOCGRS485, buf) buf[0] |= SER_RS485_ENABLED if rs485_settings is not None: if rs485_settings.loopback: buf[0] |= SER_RS485_RX_DURING_TX else: buf[0] &= ~SER_RS485_RX_DURING_TX if rs485_settings.rts_level_for_tx: buf[0] |= SER_RS485_RTS_ON_SEND else: buf[0] &= ~SER_RS485_RTS_ON_SEND if rs485_settings.rts_level_for_rx: buf[0] |= SER_RS485_RTS_AFTER_SEND else: buf[0] &= ~SER_RS485_RTS_AFTER_SEND if rs485_settings.delay_before_tx is not None: buf[1] = int(rs485_settings.delay_before_tx * 1000) if rs485_settings.delay_before_rx is not None: buf[2] = int(rs485_settings.delay_before_rx * 1000) else: buf[0] = 0 # clear SER_RS485_ENABLED fcntl.ioctl(self.fd, TIOCSRS485, buf) except IOError as e: raise ValueError('Failed to set RS485 mode: {}'.format(e))
def PPSETTIME(self, time): """ Sets the time-out (see PPGETTIME for more information). 'time' is the new time-out in seconds; floating-point values are acceptable. """ fcntl.ioctl(self._fd, PPSETTIME, floatToTimeval(time))
def PPFCONTROL(self, mask, val): """ Frobs the control lines. Since a common operation is to change one of the control signals while leaving the others alone, it would be quite inefficient for the user-land driver to have to use PPRCONTROL, make the change, and then use PPWCONTROL. Of course, each driver could remember what state the control lines are supposed to be in (they are never changed by anything else), but in order to provide PPRCONTROL, ppdev must remember the state of the control lines anyway. The PPFCONTROL ioctl is for "frobbing" control lines, and is like PPWCONTROL but acts on a restricted set of control lines. The ioctl parameter is a pointer to a struct ppdev_frob_struct: struct ppdev_frob_struct { unsigned char mask; unsigned char val; }; The mask and val fields are bitwise ORs of control line names (such as in PPWCONTROL). The operation performed by PPFCONTROL is: new_ctr = (old_ctr & ~mask) | val In other words, the signals named in mask are set to the values in val. """ fcntl.ioctl(self._fd, PPFCONTROL, struct.pack('BB', mask, val))
def grab (self, grab=1): """ Grabs all input from this node, so nothing else can read it. Using the 'grab' parameter, you can specify whether to grab (1) or ungrab (0) the node. The default is to grab. """ fcntl.ioctl(self.fd, const.EVIOCGRAB, grab)
def PPNEGOT(self, mode): """ Performs IEEE 1284 negotiation into a particular mode. Briefly, negotiation is the method by which the host and the peripheral decide on a protocol to use when transferring data. An IEEE 1284 compliant device will start out in compatibility mode, and then the host can negotiate to another mode (such as ECP). The 'mode' parameter should be one of the following constants from PPDEV: - IEEE1284_MODE_COMPAT - IEEE1284_MODE_NIBBLE - IEEE1284_MODE_BYTE - IEEE1284_MODE_EPP - IEEE1284_MODE_ECP The PPNEGOT ioctl actually does two things: it performs the on-the-wire negotiation, and it sets the behaviour of subsequent read/write calls so that they use that mode (but see PPSETMODE). """ fcntl.ioctl(self._fd, PPNEGOT, struct.pack('i', mode))
def resize(self, rows, cols): """ Resizes the child process's terminal window to *rows* and *cols* """ self.term.resize(rows, cols) s = struct.pack("HHHH", rows, cols, 0, 0) fcntl.ioctl(self.fd, termios.TIOCSWINSZ, s)
def _set_term_winsz(fd, winsz): fcntl.ioctl(fd, _TIOCSWINSZ, winsz)
def cts(self): """Read terminal status line: Clear To Send""" if not self.is_open: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I', s)[0] & TIOCM_CTS != 0
def _update_dtr_state(self): """Set terminal status line: Data Terminal Ready""" if self._dtr_state: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
def _update_rts_state(self): """Set terminal status line: Request To Send""" if self._rts_state: fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str) else: fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
def in_waiting(self): """Return the number of bytes currently in the input buffer.""" #~ s = fcntl.ioctl(self.fd, termios.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I', s)[0]
def _set_special_baudrate(self, baudrate): # use IOKit-specific call to set up high speeds buf = array.array('i', [baudrate]) fcntl.ioctl(self.fd, IOSSIOSPEED, buf, 1)
def _get_term_winsz(fd): s = struct.pack("HHHH", 0, 0, 0, 0) return fcntl.ioctl(fd, _TIOCGWINSZ, s)
def cancel(self): fcntl.ioctl(self.fd, termios.TIOCSTI, b'\0')
def netinfo(): """ 장비의 네트워크 정보를 아래와 같이 리턴한다. :return: list Ubuntu 16.04 인경우, [ { 'iface': 'docker0', 'mac': '02:42:b0:55:ab:6e', 'ip': '172.17.0.1', 'gateway': '' }, { 'iface': 'enp3s0', 'mac': '02:42:b0:55:ab:6e', 'ip': '172.17.0.1', 'gateway': '172.29.99.254' }, { 'iface': 'lo', 'mac': '', 'ip': '127.0.0.1', 'gateway': '' } ] """ list_netinfo = [] list_ifname = all_interfaces_info() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for ifname in list_ifname: result1 = {} ipinfo = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname))[20:24] ipaddr = struct.unpack("<L", ipinfo)[0] ipaddr = socket.htonl(ipaddr) ipaddr = socket.inet_ntoa(ipinfo) macinfo = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15])) macaddr = ''.join(['%02x:' % ord(char) for char in macinfo[18:24]])[:-1] macaddr = macaddr.upper() netmask = socket.inet_ntoa( fcntl.ioctl( s.fileno(), 0x891b, # SIOCGIFADDR struct.pack('256s', ifname[:15]))[20:24]) result1[netinfo_keys[0]] = ifname result1[netinfo_keys[1]] = ipaddr result1[netinfo_keys[2]] = macaddr result1[netinfo_keys[4]] = netmask list_netinfo.append(result1) with open("/proc/net/route") as fh: '''''' for line in fh: '''''' fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue for el in list_netinfo: if el['iface'] == fields[0]: el['gateway'] = socket.inet_ntoa( struct.pack("<L", int(fields[2], 16))) else: el['gateway'] = "" return list_netinfo
def get_local_ip(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15])) ret = socket.inet_ntoa(inet[20:24]) return ret
def _get_extra_flags(self): # Get mode buf = array.array('B', [0]) fcntl.ioctl(self._fd, SPI._SPI_IOC_RD_MODE, buf, True) return buf[0] & ~(SPI._SPI_LSB_FIRST | SPI._SPI_CPHA | SPI._SPI_CPOL)
# script to highlight adb logcat output for console # written by jeff sharkey, http://jsharkey.org/ # piping detection and popen() added by other android team members # Modified by Yongce Tu <yongce.tu at gmail.com> # 1. Add line number # 2. Support logcat filter args # 3. Support logcat -v brief|time|threadtime # import os, sys, re, StringIO import fcntl, termios, struct import getopt # unpack the current terminal width/height data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') HEIGHT, WIDTH = struct.unpack('hh',data) BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def format(fg=None, bg=None, bright=False, bold=False, dim=False, reset=False): # manually derived from http://en.wikipedia.org/wiki/ANSI_escape_code#Codes codes = [] if reset: codes.append("0") else: if not fg is None: codes.append("3%d" % (fg)) if not bg is None: if not bright: codes.append("4%d" % (bg)) else: codes.append("10%d" % (bg)) if bold: codes.append("1") elif dim: codes.append("2")
def _get_max_speed(self): # Get max speed buf = array.array('I', [0]) fcntl.ioctl(self._fd, SPI._SPI_IOC_RD_MAX_SPEED_HZ, buf, True) return buf[0]
def get_last_packet_timestamp(sock): ts = ioctl(sock, SIOCGSTAMP, "12345678") s, us = struct.unpack("II", ts) return s + us / 1000000.0
def getTerminalSize(): s = struct.pack('HHHH', 0, 0, 0, 0) result = fcntl.ioctl(sys.stdin.fileno(), termios.TIOCGWINSZ, s) rows, cols = struct.unpack('HHHH', result)[0:2] return rows, cols
def _get_bits_per_word(self): # Get bits per word buf = array.array('B', [0]) fcntl.ioctl(self._fd, SPI._SPI_IOC_RD_BITS_PER_WORD, buf, True) return buf[0]
def sigwinch_passthrough (sig, data): s = struct.pack("HHHH", 0, 0, 0, 0) size = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) Term.setwinsize(size[0], size[1])
def handle_resize(self, signum, frame): h, w = array('h', ioctl(self.fd, termios.TIOCGWINSZ, '\0' * 8))[:2] self.term_width = w
def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa( fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
def getHwAddr(self, ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15])) return ':'.join(['%02x' % ord(char) for char in info[18:24]])
def get_cols(): fd = 0 # stdin cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) return cr[1]
def PPWDATA(self, byte): """ Sets the data lines (if in forward mode). The ioctl parameter is a pointer to an unsigned char. """ fcntl.ioctl(self._fd, PPWDATA, struct.pack('B', byte))
def get_ip(inter): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip_addr = socket.inet_ntoa( fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', inter[:15]))[20:24]) return ip_addr
def _getSupportedResolutions(self): """Query the camera for supported resolutions for a given pixel_format. Data is returned in a list of dictionaries with supported pixel formats as the following example shows: resolution['pixelformat'] = "YUYV" resolution['description'] = "(YUV 4:2:2 (YUYV))" resolution['resolutions'] = [[width, height], [640, 480], [1280, 720] ] If we are unable to gather any information from the driver, then we return YUYV and 640x480 which seems to be a safe default. Per the v4l2 spec the ioctl used here is experimental but seems to be well supported. """ try: device = '/dev/video%d' % self.number_of_video_device supported_formats = self.__getPixelFormats(device) if not supported_formats: return None for supported_format in supported_formats: resolutions = [] framesize = v4l2.v4l2_frmsizeenum() framesize.index = 0 framesize.pixel_format = supported_format['pixelformat_int'] with open(device, 'r') as vd: try: cp = v4l2.v4l2_capability() fcntl.ioctl(vd, v4l2.VIDIOC_QUERYCAP, cp) self.cameraName = cp.card while fcntl.ioctl( vd,v4l2.VIDIOC_ENUM_FRAMESIZES,framesize) == 0: if framesize.type == v4l2.V4L2_FRMSIZE_TYPE_DISCRETE: resolutions.append([framesize.discrete.width, framesize.discrete.height]) # for continuous and stepwise, let's just use min and # max they use the same structure and only return # one result elif framesize.type == v4l2.V4L2_FRMSIZE_TYPE_CONTINUOUS or framesize.type == v4l2.V4L2_FRMSIZE_TYPE_STEPWISE: if hasattr(framesize.stepwise, 'max_width'): max_width = framesize.stepwise.max_width else: max_width = framesize.stepwise.max_height width = framesize.stepwise.min_width height = framesize.stepwise.min_height stepWidth = framesize.stepwise.step_width stepHeight = framesize.stepwise.step_height widthCounter = 1 heightCounter = 1 ########## Low resolution ######### if self._calcMCD(640,stepWidth) == stepWidth and self._calcMCD(480,stepHeight) == stepHeight: resolutions.append([640L,480L]) ########## High resolution ######### if self._calcMCD(1280L,stepWidth) == stepWidth and self._calcMCD(720L,stepHeight) == stepHeight: resolutions.append([1280L,720L]) break framesize.index = framesize.index + 1 except IOError as e: # EINVAL is the ioctl's way of telling us that there are no # more formats, so we ignore it if e.errno != errno.EINVAL: self._logger.error( "Unable to determine supported framesizes " "(resolutions), this may be a driver issue." ) return None supported_format['resolutions'] = resolutions for resolution in supported_format['resolutions']: frameinterval = v4l2.v4l2_frmivalenum() frameinterval.index = 0 frameinterval.pixel_format = supported_format['pixelformat_int'] frameinterval.width = resolution[0]; frameinterval.height = resolution[1]; framerates = [] with open(device, 'r') as fd: try: while fcntl.ioctl(fd,v4l2.VIDIOC_ENUM_FRAMEINTERVALS,frameinterval) != -1: if frameinterval.type == v4l2.V4L2_FRMIVAL_TYPE_DISCRETE: framerates.append(str(frameinterval.discrete.denominator) + '/' + str(frameinterval.discrete.numerator)) # for continuous and stepwise, let's just use min and # max they use the same structure and only return # one result stepval = 0 if frameinterval.type == v4l2.V4L2_FRMIVAL_TYPE_CONTINUOUS: stepval = 1 minval = frameinterval.stepwise.min.denominator/frameinterval.stepwise.min.numerator maxval = frameinterval.stepwise.max.denominator/frameinterval.stepwise.max.numerator if stepval == 0: stepval = frameinterval.stepwise.step.denominator/frameinterval.stepwise.step.numerator numerator = frameinterval.stepwise.max.numerator denominator = frameinterval.stepwise.max.denominator while numerator <= frameinterval.stepwise.min.numerator: while denominator <= frameinterval.stepwise.min.denominator: framerates.append(str(denominator) + '/' + str(numerator)) denominator = denominator + frameinterval.stepwise.step.denominator numerator = numerator + frameinterval.stepwise.step.numerator denominator = frameinterval.stepwise.max.denominator elif framesize.type == v4l2.V4L2_FRMSIZE_TYPE_CONTINUOUS or\ framesize.type == v4l2.V4L2_FRMSIZE_TYPE_STEPWISE: minval = frameinterval.stepwise.min.denominator/frameinterval.stepwise.min.numerator maxval = frameinterval.stepwise.max.denominator/frameinterval.stepwise.max.numerator if stepval == 0: stepval = frameinterval.stepwise.step.denominator/frameinterval.stepwise.step.numerator for cval in range(minval,maxval): framerates.append('1/' + str(cval)) break frameinterval.index = frameinterval.index + 1 except IOError as e: # EINVAL is the ioctl's way of telling us that there are no # more formats, so we ignore it if e.errno != errno.EINVAL: self._logger.error( "Unable to determine supported " "framerates (resolutions), this may " "be a driver issue." ) resolution.append(framerates) temp = [] # clean resolutions without FPS: some broken cameras # has this configuration for resolution in supported_format['resolutions']: if len(resolution[2]) > 0: temp.append(resolution) supported_format['resolutions'] = temp try: if supported_format['resolutions']: return supported_formats else: return None except: return None except Exception: self._logger.info( 'Camera error: it is not posible to get the camera capabilities', exc_info=True ) return None
def getCD(self): """Read terminal status line: Carrier Detect""" if not self._isOpen: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I', s)[0] & TIOCM_CD != 0
def get_mac_address(inter): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', inter[:15])) mac_address = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] return mac_address
def getDSR(self): """Read terminal status line: Data Set Ready""" if not self._isOpen: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I', s)[0] & TIOCM_DSR != 0
def get_ip_address(self, ifname): #��ȡIP return socket.inet_ntoa( fcntl.ioctl( self.s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]))[20:24])
def inWaiting(self): """Return the number of characters currently in the input buffer.""" #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str) s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str) return struct.unpack('I', s)[0]
def getRI(self): """Read terminal status line: Ring Indicator""" if not self._isOpen: raise portNotOpenError s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str) return struct.unpack('I', s)[0] & TIOCM_RI != 0