Beispiel #1
0
 def accept(self, timeout=60):
     tries = timeout/6
     count = 0
     self.socket.setblocking(0)
     while 1:
         try:
             conn, self.otheraddr = self.socket.accept()
         except socket.error as why:
             if why.errno == EINTR:
                 continue
             if why.errno == EAGAIN:
                 if timeout > 0 and count > tries:
                     self.socket.setblocking(1)
                     raise TimeoutError("did not accept() in time.")
                 count += 1
                 scheduler.sleep(6)
                 continue
             else:
                 raise
         else:
             break
     self.socket.setblocking(1)
     conn.setblocking(1)
     self.file = conn.makefile()
     self.conn = conn
     return self.file
Beispiel #2
0
 def go(self, callback=None):
     isreachable = False
     pinger = self._pinger
     state = PoweroffDetector.UNKNOWN
     while True:
         if state == PoweroffDetector.UNKNOWN:
             host, isreachable = pinger.reachable(self._target)[0]
             if isreachable:
                 state = PoweroffDetector.REACHABLE
                 if callback is not None:
                     callback()
             else:
                 raise RebootDetectorError(
                     "Could not reach host initially.")
         elif state == PoweroffDetector.REACHABLE:
             r_retries = pinger.retries
             while isreachable:
                 host, isreachable = pinger.reachable(self._target)[0]
                 scheduler.sleep(pinger.delay)
                 r_retries -= 1
                 if r_retries == 0:
                     raise RebootDetectorError(
                         "Target did not become unreachable in time.")
             else:
                 return True
Beispiel #3
0
def ping(host, retries=3, timeout=5, delay=1, size=64, hops=30):
    """Perform a typical "ping" to a destinatino host.
    Prints time statistics until interrupted.
    """
    pinger = get_pinger(retries, timeout, delay, size, hops)
    sum = 0
    Nxmit = 0
    Nrecv = 0
    _min = sys.maxsize
    _max = 0
    print("Pinging %s with %d bytes of data." % (host, size))
    try:
        while 1:  # escape with SIGINT (^C)
            Nxmit = Nxmit + 1
            host, rttime = pinger.ping(host)[0]
            if rttime >= 0:
                sum += rttime
                Nrecv = Nrecv + 1
                _min = min(_min, rttime)
                _max = max(_max, rttime)
                print("%-16s  %d ms" % (host, rttime))
            scheduler.sleep(pinger.delay)
    except KeyboardInterrupt:
        print("%d packets transmitted, %d packets received, %d%% packet loss" %
              (Nxmit, Nrecv, 100 - (Nxmit / Nrecv * 100)))
        print("round-trip min/avg/max = %d/%d/%d ms" %
              (_min, sum / Nrecv, _max))
Beispiel #4
0
 def accept(self, timeout=60):
     tries = timeout / 6
     count = 0
     self.socket.setblocking(0)
     while 1:
         try:
             conn, self.otheraddr = self.socket.accept()
         except socket.error as why:
             if why.errno == EINTR:
                 continue
             if why.errno == EAGAIN:
                 if timeout > 0 and count > tries:
                     self.socket.setblocking(1)
                     raise TimeoutError("did not accept() in time.")
                 count += 1
                 scheduler.sleep(6)
                 continue
             else:
                 raise
         else:
             break
     self.socket.setblocking(1)
     conn.setblocking(1)
     self.file = conn.makefile()
     self.conn = conn
     return self.file
Beispiel #5
0
def ping(host, retries=3, timeout=5, delay=1, size=64, hops=30):
    """Perform a typical "ping" to a destinatino host.
    Prints time statistics until interrupted.
    """
    pinger = get_pinger(retries, timeout, delay, size, hops)
    sum = 0
    Nxmit = 0
    Nrecv = 0
    _min = sys.maxsize
    _max = 0
    print("Pinging %s with %d bytes of data." % (host, size))
    try:
        while 1: # escape with SIGINT (^C)
            Nxmit = Nxmit + 1
            host, rttime = pinger.ping(host)[0]
            if rttime >= 0:
                sum += rttime
                Nrecv = Nrecv + 1
                _min = min(_min, rttime)
                _max = max(_max, rttime)
                print("%-16s  %d ms" % (host, rttime))
            scheduler.sleep(pinger.delay)
    except KeyboardInterrupt:
        print("%d packets transmitted, %d packets received, %d%% packet loss" % (Nxmit, Nrecv, 100-(Nxmit/Nrecv*100)))
        print("round-trip min/avg/max = %d/%d/%d ms" % (_min, sum/Nrecv, _max))
Beispiel #6
0
 def __init__(self, port=9025, logfile=None, parser=None):
     self.port = port
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.file = None
     self.conn = None
     self.envelopes = []
     self.hostname = socket.gethostname()
     self._client = None
     self._callback = None
     self._reset()
     while 1:
         try:
             self.socket.bind(("", self.port))
             break
         except socket.error as msg:
             print("couldn't bind port",
                   self.port,
                   " - ",
                   msg,
                   "retrying...",
                   file=sys.stderr)
         scheduler.sleep(5)
     self.socket.listen(50)
     self.conversation = None
     self.logfile = logfile
     self.parser = parser
Beispiel #7
0
    def _symbols(self, c, fsm):
        d = self._device
        val = self._symbolmapping[c]
        code = val & 0x1ff
        shifted = val & SHIFT
        alt = val & ALT
        meta = val & META
        compose = val & COMPOSE

        if compose:
            d.write(EV_KEY, KEY_COMPOSE, 1)
        if shifted:
            d.write(EV_KEY, KEY_LEFTSHIFT, 1)
        if alt:
            d.write(EV_KEY, KEY_LEFTALT, 1)
        if meta:
            d.write(EV_KEY, KEY_LEFTMETA, 1)
        self._presskey(code)
        if meta:
            d.write(EV_KEY, KEY_LEFTMETA, 0)
        if alt:
            d.write(EV_KEY, KEY_LEFTALT, 0)
        if shifted:
            d.write(EV_KEY, KEY_LEFTSHIFT, 0)
        if compose:
            d.write(EV_KEY, KEY_COMPOSE, 0)
        scheduler.sleep(0.1)
Beispiel #8
0
 def _specials(self, c, fsm):
     if c == "t":
         self._device.write(EV_KEY, KEY_TAB, 0)
     elif c == "n":
         self._device.write(EV_KEY, KEY_ENTER, 0)
     elif c == "r":
         self._device.write(EV_KEY, KEY_KPENTER, 0)
     elif c == "b":
         self._device.write(EV_KEY, KEY_BACKSPACE, 0)
     elif c == "e":
         self._device.write(EV_KEY, KEY_ESC, 0)
     scheduler.sleep(0.1)
Beispiel #9
0
 def _connect(self, addr, retries):
     retry = 0
     while retry < retries:
         try:
             self.sock.connect(addr)
         except socket.error as msg:
             if msg[0] == ECONNREFUSED:  # might be busy
                 scheduler.sleep(2)
                 continue
             else:
                 raise
         else:
             return
         retry += 1
Beispiel #10
0
 def _connect(self, addr, retries):
     retry = 0
     while retry < retries:
         try:
             self.sock.connect(addr)
         except socket.error as msg:
             if msg[0] == ECONNREFUSED: # might be busy
                 scheduler.sleep(2)
                 continue
             else:
                 raise
         else:
             return
         retry += 1
Beispiel #11
0
    def go(self, callback=None):
        """Start the reboot detection.

        If a callback is provided it is called after device is gone through its
        unreachable phase and is now reachable again.

        Returns a boolean value indication success.

        May raise RebootDetectorError if something is not right with the reboot process.
        """
        isreachable = False
        pinger = self._pinger
        state = RebootDetector.UNKNOWN
        while True:
            if state == RebootDetector.UNKNOWN:
                host, isreachable = pinger.reachable(self._target)[0]
                if isreachable:
                    state = RebootDetector.REACHABLE
                    if callback is not None:
                        callback()
                else:
                    raise RebootDetectorError(
                        "Could not reach host initially.")
            elif state == RebootDetector.REACHABLE:
                r_retries = pinger.retries
                while isreachable:
                    host, isreachable = pinger.reachable(self._target)[0]
                    scheduler.sleep(pinger.delay)
                    r_retries -= 1
                    if r_retries == 0:
                        raise RebootDetectorError(
                            "Target did not become unreachable.")
                else:
                    state = RebootDetector.NOTREACHABLE
            elif state == RebootDetector.NOTREACHABLE:
                r_retries = pinger.retries
                while not isreachable:
                    host, isreachable = pinger.reachable(self._target)[0]
                    scheduler.sleep(pinger.delay)
                    r_retries -= 1
                    if r_retries == 0:
                        raise RebootDetectorError(
                            "Target did not become reachable again.")
                else:
                    state = RebootDetector.REACHABLE2
                    break
        return state == RebootDetector.REACHABLE2
Beispiel #12
0
    def go(self, callback=None):
        """Start the reboot detection.

        If a callback is provided it is called after device is gone through its
        unreachable phase and is now reachable again.

        Returns a boolean value indication success.

        May raise RebootDetectorError if something is not right with the reboot process.
        """
        isreachable = False
        pinger = self._pinger
        state = RebootDetector.UNKNOWN
        while True:
            if state == RebootDetector.UNKNOWN:
                host, isreachable = pinger.reachable(self._target)[0]
                if isreachable:
                    state = RebootDetector.REACHABLE
                    if callback is not None:
                        callback()
                else:
                    raise RebootDetectorError("Could not reach host initially.")
            elif state == RebootDetector.REACHABLE:
                r_retries = pinger.retries
                while isreachable:
                    host, isreachable = pinger.reachable(self._target)[0]
                    scheduler.sleep(pinger.delay)
                    r_retries -= 1
                    if r_retries == 0:
                        raise RebootDetectorError("Target did not become unreachable.")
                else:
                    state = RebootDetector.NOTREACHABLE
            elif state == RebootDetector.NOTREACHABLE:
                r_retries = pinger.retries
                while not isreachable:
                    host, isreachable = pinger.reachable(self._target)[0]
                    scheduler.sleep(pinger.delay)
                    r_retries -= 1
                    if r_retries == 0:
                        raise RebootDetectorError("Target did not become reachable again.")
                else:
                    state = RebootDetector.REACHABLE2
                    break
        return state == RebootDetector.REACHABLE2
Beispiel #13
0
 def clear(self, delay=0):
     if self._eqcache:
         eqc = self._eqcache
         self._eqcache = {}
         while eqc:
             name, obj = eqc.popitem()
             try:
                 obj.clear()
             except:
                 logging.exception_error(
                     "environment clear: {!r}".format(obj))
     gc.collect()
     for obj in gc.garbage:
         try:
             obj.close()
         except:
             logging.exception_warning(
                 "environment garbage collect: {!r}".format(obj))
     del gc.garbage[:]
     if delay:
         scheduler.sleep(delay)
Beispiel #14
0
 def clear(self, delay=0):
     if self._eqcache:
         eqc = self._eqcache
         self._eqcache = {}
         while eqc:
             name, obj = eqc.popitem()
             try:
                 obj.clear()
             except:
                 logging.exception_error(
                     "environment clear: {!r}".format(obj))
     gc.collect()
     for obj in gc.garbage:
         try:
             obj.close()
         except:
             logging.exception_warning(
                 "environment garbage collect: {!r}".format(obj))
     del gc.garbage[:]
     if delay:
         scheduler.sleep(delay)
Beispiel #15
0
 def __init__ (self, port=9025, logfile=None, parser=None):
     self.port = port
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.file = None
     self.conn = None
     self.envelopes = []
     self.hostname = socket.gethostname()
     self._client = None
     self._callback = None
     self._reset()
     while 1:
         try:
             self.socket.bind(("", self.port))
             break
         except socket.error as msg:
             print ("couldn't bind port",self.port," - ",msg,"retrying...", file=sys.stderr)
         scheduler.sleep(5)
     self.socket.listen(50)
     self.conversation = None
     self.logfile = logfile
     self.parser = parser
Beispiel #16
0
 def __do_command(self, cmdstr, hosts):
     for host in hosts:
         if isinstance(host, list):
             s = []
             for hle in host:
                 s.append(str(hle))
             cmdstr += " ".join(s)
         else:
             cmdstr += " %s" % host
     rqst = "-size %d -timeout %d -retries %d -delay %d %s\n" % \
                 (self.size, self.timeout, self.retries, self.delay, cmdstr)
     self._write(rqst)
     # now try and get all of pyntping's output
     resstr = self._read(4096)
     scheduler.sleep(1)
     while self.fstat().st_size != 0:
         next = self._read(4096)
         if next:
             resstr += next
         scheduler.sleep(1)
     # we should have got a tuple of tuples
     result =  eval(resstr, {}, {})
     return result
Beispiel #17
0
 def go(self, callback=None):
     isreachable = False
     pinger = self._pinger
     state = PoweroffDetector.UNKNOWN
     while True:
         if state == PoweroffDetector.UNKNOWN:
             host, isreachable = pinger.reachable(self._target)[0]
             if isreachable:
                 state = PoweroffDetector.REACHABLE
                 if callback is not None:
                     callback()
             else:
                 raise RebootDetectorError("Could not reach host initially.")
         elif state == PoweroffDetector.REACHABLE:
             r_retries = pinger.retries
             while isreachable:
                 host, isreachable = pinger.reachable(self._target)[0]
                 scheduler.sleep(pinger.delay)
                 r_retries -= 1
                 if r_retries == 0:
                     raise RebootDetectorError("Target did not become unreachable in time.")
             else:
                 return True
Beispiel #18
0
 def __do_command(self, cmdstr, hosts):
     for host in hosts:
         if isinstance(host, list):
             s = []
             for hle in host:
                 s.append(str(hle))
             cmdstr += " ".join(s)
         else:
             cmdstr += " %s" % host
     rqst = "-size %d -timeout %d -retries %d -delay %d %s\n" % \
                 (self.size, self.timeout, self.retries, self.delay, cmdstr)
     self._write(rqst)
     # now try and get all of pyntping's output
     resstr = self._read(4096)
     scheduler.sleep(1)
     while self.fstat().st_size != 0:
         next = self._read(4096)
         if next:
             resstr += next
         scheduler.sleep(1)
     # we should have got a tuple of tuples
     result = eval(resstr, {}, {})
     return result
Beispiel #19
0
    def _stickies(self, c, fsm):
        if c == "S" and not self._shift:
            self._shift = 1
            self._device.write(EV_KEY, KEY_LEFTSHIFT, 1)
        elif c == "s" and self._shift:
            self._shift = 0
            self._device.write(EV_KEY, KEY_LEFTSHIFT, 0)

        elif c == "C" and not self._ctrl:
            self._ctrl = 1
            self._device.write(EV_KEY, KEY_LEFTCTRL, 1)
        elif c == "c" and self._ctrl:
            self._shift = 0
            self._device.write(EV_KEY, KEY_LEFTCTRL, 0)

        elif c == "A" and not self._alt:
            self._alt = 1
            self._device.write(EV_KEY, KEY_LEFTALT, 1)
        elif c == "a" and self._alt:
            self._alt = 0
            self._device.write(EV_KEY, KEY_LEFTALT, 0)

        elif c == "M" and not self._meta:
            self._meta = 1
            self._device.write(EV_KEY, KEY_LEFTMETA, 1)
        elif c == "m" and self._meta:
            self._meta = 0
            self._device.write(EV_KEY, KEY_LEFTMETA, 0)

        elif c == "O" and not self._compose:
            self._compose = 1
            self._device.write(EV_KEY, KEY_COMPOSE, 1)
        elif c == "o" and self._compose:
            self._compose = 0
            self._device.write(EV_KEY, KEY_COMPOSE, 0)

        scheduler.sleep(0.1)
Beispiel #20
0
def _co_function():
    import sys
    from pycopia.OS import scheduler
    sys.stdout.write("hello from co_function\n")
    scheduler.sleep(5)
    return None
Beispiel #21
0
 def _upper(self, c, fsm):
     val = _LETTERS[c.lower()]
     self._device.write(EV_KEY, KEY_LEFTSHIFT, 1)
     self._presskey(val)
     self._device.write(EV_KEY, KEY_LEFTSHIFT, 0)
     scheduler.sleep(0.1)
Beispiel #22
0
 def _lower(self, c, fsm):
     val = _LETTERS[c]
     self._presskey(val)
     scheduler.sleep(0.1)
Beispiel #23
0
 def _backslash(self, c, fsm):
     self._presskey(KEY_BACKSLASH)
     scheduler.sleep(0.1)
Beispiel #24
0
 def _digit(self, c, fsm):
     val = _DIGITS[c]
     self._presskey(val)
     scheduler.sleep(0.1)
Beispiel #25
0
def _sub_function():
    from pycopia.OS import scheduler
    scheduler.sleep(5)
    return None
Beispiel #26
0
 def loop(self, poller, timeout=-1.0, callback=NULL):
     while self._procs:
         poller.poll(timeout)
         callback(self)
         if scheduler.get_scheduler():  # wait for any restarts
             scheduler.sleep(1.5)
Beispiel #27
0
 def _control(self, c, fsm):
     val = _LETTERS[chr(ord(c) | 0x60)]
     self._device.write(EV_KEY, KEY_LEFTCTRL, 1)
     self._presskey(val)
     self._device.write(EV_KEY, KEY_LEFTCTRL, 0)
     scheduler.sleep(0.1)
Beispiel #28
0
 def _keycode(self, c, fsm):
     val = _VALUEMAP[fsm.keyname]
     self._presskey(val)
     scheduler.sleep(0.1)
Beispiel #29
0
 def _space(self, c, fsm):
     self._presskey(KEY_SPACE)
     scheduler.sleep(0.1)
Beispiel #30
0
 def loop(self, poller, timeout=-1.0, callback=NULL):
     while self._procs:
         poller.poll(timeout)
         callback(self)
         if scheduler.get_scheduler():  # wait for any restarts
             scheduler.sleep(1.5)
Beispiel #31
0
# run module as root like this:
# python -i event.py
if __name__ == "__main__":
    from pycopia.OS import Input

    class MockDevice(object):
        def write(self, evtype, code, value):
            print(("%s %s %s" % (evtype, code, value)))
        def close(self):
            pass

    #fo = MockDevice()
    fo = Input.EventDevice()
    fo.find(name="keyboard")
    g = KeyEventGenerator(fo)
    scheduler.sleep(2)
    expected = (ascii.lowercase + "\n" + ascii.uppercase + "\n" + ascii.digits + "\n" +
        r"""!"#$&'()*+,-./:;<=>?@[\]^_`{|}~""" + "\n" + "ab%c\tDEF\tghi%\n" )
    g('sent = """')
    g(ascii.lowercase)
    g("\n")
    g(ascii.uppercase)
    g("\n")
    g(ascii.digits)
    g("\n")
    # You have to slash escape the "<" and \ itself.
    g( r"""!"#$&'()*+,-./:;\<=>?@[\\]^_`{|}~""" )
    g("\n")
    g("ab\%c<TAB>%Sdef%s%Ci%cghi%%" )
    g("\n")
    g('"""\n')