Exemple #1
0
    def __init__(self, force_ssl=True, telnet_tls=True, **kwargs):
        """
        Called just like telnetlib.Telnet(), with these extra options:

        force_ssl  - If True, force SSL negotiation as soon as connected.
                     Defaults to True.
        telnet_tls - If true, allow TELNET TLS negotiation after non-ssl
                     connection.  Defaults to True.

        Also accepts args to ssl.wrap_socket()

        If force_ssl is True, plaintext connections aren't allowed.
        If force_ssl is False, and telnet_tls is True, the connection
        will be plaintext until the server negotiates TLS, at which
        time the connection will be secured.
        If both are False, the connection will be plaintext.
        """
        self.in_tls_wait = False
        self.tls_write_buffer = b''
        self.secure = False
        self.force_ssl = force_ssl
        self.allow_telnet_tls = telnet_tls
        self.ssltelnet_callback = None
        ssl_argnames = {
            'keyfile', 'certfile', 'cert_reqs', 'ssl_version',
            'ca_certs', 'suppress_ragged_eofs', 'ciphers',
        }
        self.ssl_args = {k: v for k, v in kwargs.items() if k in ssl_argnames}
        telnet_args = {k: v for k, v in kwargs.items() if k not in ssl_argnames}
        Telnet.__init__(self, **telnet_args)
        Telnet.set_option_negotiation_callback(self,
            self._ssltelnet_opt_cb)
Exemple #2
0
 def __init__ (self, port=monBase):  # 1st usable IP = monBase +2  # host='localhost', 
   Telnet.__init__(self)
   self.host = 'localhost'
   self.port = port
   self.history = History()
   #self.rlock = RLock()  # from man kvm:  "Only one TCP connection at a time is accepted"
   if self.trace: self.set_debuglevel(1)
Exemple #3
0
 def __init__(self, host_port_timeout, secret=None, **kwargs):
     self.sock = None
     if isinstance(host_port_timeout, str):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     (status, length), content = self._read()
     if status == 107 and secret is not None:
         self.auth(secret, content)
Exemple #4
0
  def __init__(self, host, verbose = False):
    self._host = host
    self._verbose = verbose
    self._mode = MODE_INIT

    Telnet.__init__(self, host)

    self._mode = MODE_CONNECTED
Exemple #5
0
 def __init__(self, host, port):
     try:
         Telnet.__init__(self, host, port)
     except:
         print "Cannot connect to:", host, port
     self.prompt = []
     self.prompt.append(re.compile('/[^>]*> '))
     self.timeout = 2
Exemple #6
0
 def __init__(self,host,port):
     try:
         Telnet.__init__(self,host,port)
     except:
         print "Cannot connect to:", host, port
     self.prompt = []
     self.prompt.append( re.compile('/[^>]*> ') )
     self.timeout = 2
Exemple #7
0
    def __init__(self, stream, logfile):

        Telnet.__init__(self, host=None)
        self.stream = stream
        self.logfile = logfile
        self.eof = 0
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.connect(stream)
Exemple #8
0
    def Expect(self, pat, wait=2, nowait=False):
        self.fExpecting = True
        if wait == None:
            wait = 0.5
        else:
            wait = float(wait)
        found = None

        m = None
        if not nowait:
            if not self.fInteractionMode:

                output = self.expect(["%s" % (pat)], float(wait))
                self.output = output[2]
                m = sre.search('%s' % (pat), self.output, sre.M | sre.DOTALL)

            else:
                interval = 0.1
                counter = 0
                max_counter = round(float(wait) / interval) + 1
                interactionpat = '(%s)(.*)' % pat
                while counter < max_counter:
                    counter += 1
                    m = sre.search(interactionpat, self.InteractionBuffer,
                                   sre.M | sre.DOTALL)
                    if m:
                        self.InteractionMatch = m.group(0)
                        self.InteractionBuffer = m.group(1)  #.decode("utf-8")
                        break
                    time.sleep(interval)
        else:
            m = sre.search(pat, self.output, sre.M | sre.DOTALL)
        self.seslog.flush()
        self.fExpecting = False
        if not m:
            raise Exception('Expect("%s", %f) Failed' % (pat, float(wait)))
        self.match = m.group()
        global reSessionClosed
        mSesClosed = sre.search(reSessionClosed, self.output)
        isalive = self.isalive()
        if (self.Connect2SUTDone):
            if (mSesClosed):
                command = self.attrs['CMD']
                self.error("Session(%s) has been closed by remote host!" %
                           (self.sutname))
                if command.find('telnet') != -1:
                    host = ""
                    port = 23
                    args = command.split(' ')
                    if len(args) == 2:
                        host = args[1]
                    elif len(args) == 3:
                        host = args[1]
                        port = args[2]
                    spawn.__init__(self, host, port)
                self.set_debuglevel(1)
                self.Login2SUT()
        return self.output
 def __init__(self, host_port_timeout, secret=None, **kwargs):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     (status, length), content = self._read()
     if status == 107 and secret is not None:
         self.auth(secret, content)
     elif status != 200:
         logging.error('Connecting failed with status: %i' % status)
Exemple #10
0
 def __init__(self, host_port_timeout, secret=None, **kwargs):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     (status, length), content = self._read()
     if status == 107 and secret is not None:
         self.auth(secret, content)
     elif status != 200:
         logging.error('Connecting failed with status: %i' % status)
Exemple #11
0
    def Expect(self,pat , wait=2, nowait=False):
        self.fExpecting=True
        if wait==None:
            wait=0.5
        else:
            wait = float(wait)
        found =None


        m =None
        if not nowait:
            if not self.fInteractionMode:

                output =self.expect(["%s"%(pat)],float(wait))
                self.output=output[2]
                m =sre.search('%s'%(pat), self.output, sre.M|sre.DOTALL)

            else:
                interval=0.1
                counter =0
                max_counter=round(float(wait)/interval)+1
                interactionpat = '(%s)(.*)'%pat
                while counter<max_counter:
                    counter+=1
                    m =sre.search(interactionpat,self.InteractionBuffer,sre.M|sre.DOTALL)
                    if m:
                        self.InteractionMatch=m.group(0)
                        self.InteractionBuffer=m.group(1)#.decode("utf-8")
                        break
                    time.sleep(interval)
        else:
            m = sre.search(pat,self.output, sre.M|sre.DOTALL)
        self.seslog.flush()
        self.fExpecting=False
        if not m:
            raise Exception('Expect("%s", %f) Failed'%(pat,float(wait)))
        self.match = m.group()
        global reSessionClosed
        mSesClosed= sre.search(reSessionClosed,self.output)
        isalive = self.isalive()
        if (self.Connect2SUTDone):
            if (mSesClosed):
                command = self.attrs['CMD']
                self.error("Session(%s) has been closed by remote host!"%(self.sutname))
                if command.find('telnet')!=-1:
                    host=""
                    port=23
                    args = command.split(' ')
                    if len(args)==2:
                        host = args[1]
                    elif len(args)==3:
                        host= args [1]
                        port = args[2]
                    spawn.__init__(self, host, port)
                self.set_debuglevel(1)
                self.Login2SUT()
        return self.output
Exemple #12
0
 def __init__(self, host, port):
     self.inited = False
     try:
         Telnet.__init__(self, host, port)
         self.inited = True
     except:
         print "Telnet initialization failed (no auralink server running?)"
     self.prompt = []
     self.prompt.append(re.compile('/[^>]*> '))
     self.timeout = 2
    def __init__(self, host=None, port=Defaults.port, keyfile=Defaults.keyfile, certfile=Defaults.certfile, verifyfile=Defaults.verifyfile):
        ## Same as normal, but make it secure:
        self.ctx = SSL.Context(SSL.SSLv23_METHOD)
        self.ctx.set_options(SSL.OP_NO_SSLv2)

        if verifyfile:
            self.ctx.set_verify(SSL.VERIFY_PEER, self.verify_cb) # Demand a certificate
            self.ctx.load_verify_locations(os.path.join(dir, verifyfile))
        self.ctx.use_privatekey_file (keyfile)
        self.ctx.use_certificate_file(certfile)
        Telnet.__init__(self, host, port)
Exemple #14
0
 def __init__(self,
              host=None,
              port=5024,
              timeout=10,
              ChannelList="(@1001:1040,2001:2040,3001:3040)"):
     Telnet.__init__(self)
     self.Ch_List = ChannelList
     self.telnet_prompt = "Tharsis> "
     if host is not None:
         print('Connecting')
         self.open(host, port, timeout)
    def __init__(self, hostname, port, timeout, pipe_in, pipe_out, keep_alive=30, poll_interval=0.125):
        self.pipe_in = pipe_in
        self.pipe_out = pipe_out

        self.logger = logging.getLogger('teamspeak3.TeamspeakConnection')

        self.commands_unresponded = deque()

        self.keep_alive = keep_alive
        self.poll_interval = poll_interval
        Telnet.__init__(self, hostname, port, timeout)
 def __init__(self,
              host='192.168.99.3',
              port=5024,
              timeout=10,
              ChannelList="(@1001:1040,2001:2040,3001:3040)"):
     Telnet.__init__(self)
     self.Ch_List = ChannelList
     self.working_tc_lower_limit = 8
     self.working_tc_upper_limit = 2000
     self.telnet_prompt = "Tharsis> "
     if host is not None:
         self.open(host, port, timeout)
Exemple #17
0
 def __init__(self, host_port_timeout, **opts):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     self.secret = opts.get('secret', None)
     Telnet.__init__(self, *host_port_timeout)
     # Read first response from Varnish
     (status, length), content = self._read()
     if status == 107 and self.secret:
         # Authenticate before continuing.
         m = hashlib.sha256()
         challenge = content[:32]
         m.update(challenge + '\n' + self.secret + '\n' + challenge + '\n')
         self.fetch('auth ' + m.hexdigest())
Exemple #18
0
 def __init__(self, server):
     host_port_timeout = server.addr
     secret = server.secret
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     # Eat the preamble ...
     #self.read_until("Type 'quit' to close CLI session.\n\n")
     if secret:
         self.auth_token = self.read_until("Authentication required.\n\n").split('\n')[1]
         resp = self.auth(VarnishAuth(secret).auth_hash(self.auth_token))
         self.read_until("\n")
     else:
         self.read_until("Type 'quit' to close CLI session.\n\n")
Exemple #19
0
 def __init__(self, host_port_timeout, **opts):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     self.secret = opts.get('secret', None)
     Telnet.__init__(self, *host_port_timeout)
     # Read first response from Varnish
     (status,
      length), content = map(int,
                             self.read_until('\n').strip().split()), ''
     while len(content) < length:
         content += self.read_until('\n')
     self.read_until('\n')
     if status == 107:
         # Authenticate before continuing.
         m = hashlib.sha256()
         challenge = content[:32]
         m.update(challenge + '\n' + self.secret + '\n' + challenge + '\n')
         self.fetch('auth ' + m.hexdigest())
    def __init__(self, host, port, name, secret=None, version=30, timeout=5):
        # Try to establish connection.
        Telnet.__init__(self, host, port, timeout)
        self.name = name
        self.version = version
        (status, length), content = self._read()

        # Authentication requested?
        if status == 107:
            if secret:
                self._auth(secret, content)
            else:
                raise Varnish.Exception(self.error_messages['missing_secret'])
        # Failed connection?
        elif status != 200:
            raise Varnish.Exception(self.error_messages['failed_connection'] % {
                'status': status,
            })
Exemple #21
0
    def __init__(self,
                 hostname,
                 port,
                 timeout,
                 pipe_in,
                 pipe_out,
                 keep_alive=30,
                 poll_interval=0.125):
        self.pipe_in = pipe_in
        self.pipe_out = pipe_out

        self.logger = logging.getLogger('teamspeak3.TeamspeakConnection')

        self.commands_unresponded = deque()

        self.keep_alive = keep_alive
        self.poll_interval = poll_interval
        Telnet.__init__(self, hostname, port, timeout)
Exemple #22
0
    def __init__(self, host, port, name, secret=None, version=30, timeout=5):
        # Try to establish connection.
        Telnet.__init__(self, host, port, timeout)
        self.name = name
        self.version = version
        (status, length), content = self._read()

        # Authentication requested?
        if status == 107:
            if secret:
                self._auth(secret, content)
            else:
                raise Varnish.Exception(self.error_messages['missing_secret'])
        # Failed connection?
        elif status != 200:
            raise Varnish.Exception(
                self.error_messages['failed_connection'] % {
                    'status': status,
                })
Exemple #23
0
    def __init__(self,name,attrs={},logger=None, logpath=None):
        baseSession.__init__(self, name,attrs,logger,logpath)

        host=""
        port=23
        reHostOnly=  sre.compile('\s*telnet\s+([\d.\w\-_]+)\s*',sre.I)
        reHostPort = sre.compile('\s*telnet\s+([\d.\w]+)\s+(\d+)', sre.I )
        command = attrs.get('CMD')
        m1=sre.match(reHostOnly, command)
        m2=sre.match(reHostPort, command)
        if m1:
            host= m1.groups(1)[0]
        elif m2:
            host= m2.groups(1)[0]
            port= m2.groups(2)[0]

        spawn.__init__(self, str(host), port)
        self.set_debuglevel(0)
        self.Login2SUT()
        self.Connect2SUTDone=True
Exemple #24
0
    def __init__(self, name, attrs={}, logger=None, logpath=None):
        baseSession.__init__(self, name, attrs, logger, logpath)

        host = ""
        port = 23
        reHostOnly = sre.compile('\s*telnet\s+([\d.\w\-_]+)\s*', sre.I)
        reHostPort = sre.compile('\s*telnet\s+([\d.\w]+)\s+(\d+)', sre.I)
        command = attrs.get('CMD')
        m1 = sre.match(reHostOnly, command)
        m2 = sre.match(reHostPort, command)
        if m1:
            host = m1.groups(1)[0]
        elif m2:
            host = m2.groups(1)[0]
            port = m2.groups(2)[0]

        spawn.__init__(self, str(host), port)
        self.set_debuglevel(0)
        self.Login2SUT()
        self.Connect2SUTDone = True
Exemple #25
0
    def __init__(self, HOST=None, PORT=23, TIMEOUT=None, USER=None, PD=None, chk_err=r"((E|e)rror)|((F|f)ailed)",
                 chk_user=None, chk_password=None, chk_success=None):
        if not TIMEOUT:
            # 如果超时时间没有设置则调用父类构造方法进行初始化
            # super(myTelnet, self).__init__(host=HOST, port=PORT)
            Telnet.__init__(self, host=HOST, port=PORT)
        else:
            # super(myTelnet, self).__init__(host=HOST, port=PORT,timeout=TIMEOUT)
            Telnet.__init__(self, host=HOST, port=PORT, timeout=TIMEOUT)

        print("self:", self.__dict__)
        """调用父类初始化后,检查相关参数,如果关键参数缺失则直接返回异常,否则直接使用参数自动登录并返回结果
        self.sock
        USER 			用户名
        PD 				密码
        chk_user 		输入用户名提示字符串
        chk_password 	输入密码提示字符串
        chk_success 	登录成功提示字符串
        """
        if (not self.sock) or (not USER) or (not PD) or (not chk_user) or (not chk_password) or (not chk_success):
            self. login = False
        else:
            self. login = self.tel_login(USER, PD, chk_err, chk_user, chk_password, chk_success)
 def __init__(self, host = 'localhost', port = 9198, auto = True):
   Telnet.__init__(self)
   self.host, self.port, self.connected = host, port, False
   if auto:
     self._connect()
 def __init__(self, host_port_timeout):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     self.fetch(None)
Exemple #28
0
 def __init__(self, address, port=23, **kwargs):
     Telnet.__init__(self)
     super().__init__(address, port, **kwargs)
     self._start_prompt = None
Exemple #29
0
 def __init__(self, host, port):
     Telnet.__init__(self, host, port)
     self.timeout = 5
     # Go into data mode
     self.data()
Exemple #30
0
 def __init__(self, host_port_timeout):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
 def __init__(self, host, port):
     Telnet.__init__(self, host, port)
     self.prompt = [re.compile("/[^>]*> ")]
     self.timeout = 5
Exemple #32
0
 def __init__(self):
     Telnet.__init__(self)
     self.set_option_negotiation_callback(CompressedTelnet.handle_stuff)
 def __init__(self, host, port):
     Telnet.__init__(self, host, port)
     self.prompt = []
     self.sock.sendall(IAC + NOP)
     self.prompt.append(re.compile('/[^>]*> '))
     self.timeout = 5
Exemple #34
0
    def __init__(self, host, verbose):

        Telnet.__init__(self, host)
        self.verbose = verbose
Exemple #35
0
 def __init__(self,
              host=None,
              port=0,
              timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
     Telnet.__init__(self, host=host, port=port, timeout=timeout)
Exemple #36
0
 def __init__(self, host_port_timeout):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     # Eat the preamble ...
     self.read_until("Type 'quit' to close CLI session.\n\n")
Exemple #37
0
 def __init__(self, host, port):
     Telnet.__init__(self, host, port)
     self.prompt = []
     self.prompt.append(re.compile('/[^>]*> '))
     self.timeout = 5
 def __init__(self, *args):
     Telnet.__init__(self, *args)
     self.read_until("Type 'quit' to close CLI session.\n\n")
Exemple #39
0
 def __init__(self,host,port):
     Telnet.__init__(self,host,port)
     self.prompt = [re.compile('/[^>]*> '.encode('utf-8'))]
     self.timeout = 5
Exemple #40
0
 def __init__(self,host,port):
     Telnet.__init__(self,host,port)
     self.prompt = []
     self.prompt.append( re.compile('/[^>]*> ') )
     self.timeout = 2
Exemple #41
0
 def __init__(self):
     Telnet.__init__(self)
     self.set_option_negotiation_callback(CompressedTelnet.handle_stuff)
Exemple #42
0
 def __init__(self, host_port_timeout):
     if isinstance(host_port_timeout, basestring):
         host_port_timeout = host_port_timeout.split(':')
     Telnet.__init__(self, *host_port_timeout)
     # Eat the preamble ...
     self.read_until("Type 'quit' to close CLI session.\n\n")
Exemple #43
0
    def __init__(self, host, verbose):

        Telnet.__init__(self, host)
        self.verbose = verbose