当前位置: 首页>>代码示例>>Python>>正文


Python telnetlib.Telnet类代码示例

本文整理汇总了Python中telnetlib.Telnet的典型用法代码示例。如果您正苦于以下问题:Python Telnet类的具体用法?Python Telnet怎么用?Python Telnet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Telnet类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

    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)
开发者ID:revarbat,项目名称:ssltelnet,代码行数:32,代码来源:__init__.py

示例2: tlnt_connect

def tlnt_connect(doc, timeout):
    print2('connecting')
    tn = Telnet(doc['server'])
    print2('sending username')
    s = tn.read_until(b'Username: ', timeout)
    cmd = doc['login'] + '\n\r'
    tn.write(cmd.encode('ascii'))
    print2('sending password')
    s = tn.read_until(b'Password: ', timeout)
    cmd = doc['password'] + '\n\r'
    tn.write(cmd.encode('ascii'))
    t = tn.expect([b'\r\n/', b'\r\nUser authorization failure\r\n'])
    if t[0] in [1, -1]:
        tn.close()
        return
    s = t[2]
    s = s.decode('ascii')
    i1 = s.find('AT')
    i2 = s.find('/')
    dd = s[i1+3:i2]
    hh = s[i2+1:i2+3]
    doc['dd2'] = dd
    doc['hh2'] = hh
    hhh = 24*int(dd) + int(hh)
    hhh -= int(doc['hh'])
    if hhh < 0:
        hhh = 0
    doc['dd1'] = '%d' % (hhh/24)
    doc['hh1'] = '%d' % (hhh%24)
    return tn
开发者ID:ivanovev,项目名称:ascft,代码行数:30,代码来源:ascft.py

示例3: getchannellist

def getchannellist(host="192.168.1.23", port=6419):
	t = Telnet(host, port)
	t.write("LSTE\nQUIT\n")
	items = t.read_all().split("\r\n")
	#lines = filter(lambda s: s.startswith("250"), lines)
#	items = map(lambda s: s[4:].split(":"), lines)
	return items
开发者ID:VollMich,项目名称:vdrcontrol,代码行数:7,代码来源:test.py

示例4: connectToServer

def connectToServer(hostIP = "10.10.100.254", port = 8899):
    HOST = hostIP #Host IP Address
    PORT = port   #Host port number

    pingStr = "ping "+HOST #Attempt to ping host
    if (os.system(pingStr)==0): #Host able to be pinged
        print "Robot found...", #Comma prevents printed line from wrapping
        try: #Attempt to connect to remote host
            tn = Telnet(host = HOST, port = PORT)
            print "Connected!"
        except Exception as E: #Failed connection
            print "Connection failed!"
            raise E
    else:                       #Host not found
        print "Host not found"
        raise ValueError('Could not connect to a host')

    print "Transmitting..."
    cmdSet = [['SPL','!C'], #Clear buffer
              ['SPL','!?'], #Request command buffer
              ['SPL','!N'], #Request ID
              ['CMD','1',50,51,52], #Transmit commands
              ['CMD','A',98,99,100],
              ['SPL','!?'], #Request command buffer
              ['SPL','!N']] #Request ID
    cmdSetStr = cmdSet2Str(cmdSet)
    tn.write(cmdSetStr)

    sleep(0.5) #Wait after transmitting
    return tn
开发者ID:jttaufa,项目名称:Rattus2,代码行数:30,代码来源:Telnet_RXTX.py

示例5: MitutoyoConnection

class MitutoyoConnection(object):
    # telnet connection to terminal server
    host = "10.1.1.35"
    port = 10001
    def __init__(self):
        try:
            self.telnet = Telnet(self.host, self.port)
        except:
            print("Cannot connect to mitutoyo host!! Check connections and try again or use manual entry")
            self.telnet = None

    def queryGauges(self):
        radialFloats = []
        for gaugeNum in range(1,6):
            self.telnet.write("D0%i\r\n"%gaugeNum)
            gaugeOutput = self.telnet.read_until("\r", 1)
            try:
                gauge, val = gaugeOutput.strip().split(":")
                gauge = int(gauge)
                val = float(val)
                assert gauge == gaugeNum
                print("gauge %i: %.4f"%(gauge, val))
            except:
                raise RuntimeError("Failed to parse gauge %i output: %s"%(gaugeNum, gaugeOutput))
            radialFloats.append(val)
        return radialFloats
开发者ID:csayres,项目名称:fitPlateProfile,代码行数:26,代码来源:mitutoyo.py

示例6: __init__

    class Session:
        def __init__(self, host, port, username, password):
            self.telnet = Telnet(host, port, 5)
            self.read_until("Login id:")
            self.write(username +"\n")
            self.read_until("Password:")
            self.write(password +"\n")
            self.read_until("Welcome root.HELP for a list of commands")

        def read_until(self, text):
            self.telnet.read_until(text.encode('ascii'), 5)

        def write(self, text):
            self.telnet.write(text.encode('ascii'))

        def is_user_registered(self, username):
            self.write("verify %s\n" % username)
            res = self.telnet.expect([b"exists", b"does not exist"])
            return res[0] == 0

        def create_user(self, username, password):
            self.write("adduser %s %s\n" % (username, password))
            self.read_until("User %s added" % username)

        def reset_password(self, username, password):
            self.write("setpassword %s %s\n" % (username, password))
            self.read_until("Password for %s reset" % username)

        def quit(self):
            self.write("quit\n")
开发者ID:galaktika81,项目名称:python_training_mantis,代码行数:30,代码来源:james.py

示例7: is_host_alive

def is_host_alive(host, port=None):
  """it checks whether a host is alive by connecting using Telnet
  Telnet is also necessary when a board behind a router.

  if a message of the exception is "Connection refused",
  it means that the host is alive, but telnet is not running on the port 'port'

  @param port: a port Telnet should connect to, default is None
  @type port: integer
  @return: result of check
  @rtype: boolean
  """
  CONNECTION_REFUSED = "Connection refused"
  telnet = Telnet()
  try:
    timeout_sec = 3
    print "is_host_alive: trying to connect by Telnet, host=%s, port=%s, timeout_sec=%s" % (host, port, timeout_sec)
    telnet.open(host, port, timeout_sec)
    telnet.close()
    return True
  except socket.error as exc:
    print exc
    if CONNECTION_REFUSED in str(exc):
      return True
    return False
开发者ID:vsuhak,项目名称:vic_test,代码行数:25,代码来源:Helpers.py

示例8: testWelcomeMessage

 def testWelcomeMessage(self):
     """On connecting the server sends a 220 response with a welcome message."""
     client = Telnet('localhost', 1025)
     self.assertEqual(client.read_some(),
                      '220 test node.js smtpevent server 0.0.2\r\n'
                      )
     client.close()
开发者ID:femto113,项目名称:node-smtpevent,代码行数:7,代码来源:sequential.py

示例9: cmd

 def cmd(self, word):
     """Connect and send a 4letter command to Zookeeper.
     """
     # Zookeeper closes the socket after every command, so we must reconnect every time.
     tn = Telnet(self.host, self.port, self.timeout)
     tn.write('{}\n'.format(word))
     return tn.read_all()
开发者ID:funollet,项目名称:nagios-plugins,代码行数:7,代码来源:check_zookeeper.py

示例10: send_config

 def send_config(self, config):
     session = Telnet(self.url_ip, self.url_port)
     result = self.send_and_wait(session, '\r\n')
     for line in config.splitlines():
         result = self.send_and_wait(session, line)
     session.close()
     return result
开发者ID:networkop,项目名称:rest-blog-unl-client,代码行数:7,代码来源:device.py

示例11: get

def get(host="localhost", port=4242):
    tel = Telnet(host, port)
    _get(tel)
    tel.write("content.location.href")
    result = _get(tel)
    tel.close()
    return result[0].strip('"')
开发者ID:brejoc,项目名称:supergenpass,代码行数:7,代码来源:firefox_url.py

示例12: main

def main():

    usage = "usage: %prog [options] GRIDFTP_SERVER_FQDN GRIDFTP_SERVER_PORT"
    parser = OptionParser(usage)
    parser.add_option('--timeout', type='int', default=5,
                      help="Telnet timeout value in seconds")
    (options, args) = parser.parse_args()

    if len(args) != 2:
        raise Exception('Number Of Args != 2')
    gridftp_server_name = args[0]
    gridftp_server_port = args[1]

    try:
        gridftp_connection = Telnet(gridftp_server_name, gridftp_server_port, options.timeout)
        output = gridftp_connection.read_until('ready.', options.timeout)
        for txt in ['220', 'GridFTP Server', 'ready']:
            if txt not in output:
                raise Exception()
        gridftp_connection.close()

        print 'PYGLIDEIN_RESOURCE_GRIDFTP=True'
        print '- update:true'
    except:
        print 'PYGLIDEIN_RESOURCE_GRIDFTP=False'
        print '- update:true'
开发者ID:IIHE,项目名称:pyglidein,代码行数:26,代码来源:gridftp_test.py

示例13: run

    def run(self):
        if self.fileType == "python":
            try:
                connection = Telnet('127.0.0.1', 7002, timeout=3)
            except:
                print "Failed"
                return
            mCmd = self.PY_CMD_TEMPLATE.format(path=self.scriptPath, cmd=self.script)
        else:
            try:
                connection = Telnet('127.0.0.1', 7001, timeout=3)
            except:
                print "Failed"
            mCmd = self.scriptRaw

        system = sys.platform
        if system == "linux2":
            connection.write(mCmd)
        elif system == "darwin":
            connection.write(mCmd.encode(encoding='UTF-8'))
        else:
            connection.write(mCmd.encode(encoding='UTF-8'))
        connection.close()

        print self.fileType + " executed"
开发者ID:minoue,项目名称:VtoM,代码行数:25,代码来源:vtom.py

示例14: __init__

 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)
开发者ID:jowolf,项目名称:evirt,代码行数:7,代码来源:kvm_monitor.py

示例15: __init__

class voip:
    only_number = re.compile('.*RING;\d*;(\d*);.*')
    fritzbox = None
    telnet = None
    
    def __init__(self, fritzbox="192.168.178.1"):
        
        self.fritzbox = fritzbox
        
        nc = notifier()
        self.connect()
        telnet = self.telnet
        
        logging.info('Connected to Telnet: {0}'.format(str(telnet)))

        while True:
            try:
                logging.info('Waiting for nother event')
            
                try:
                    data = telnet.read_until('POTS;', 300) # maybe read while 1 and then do
                except EOFError:
                    logging.warning('Lost connection to telnet server')
                    self.reconnect()
                
                
                number = '\n'.join(self.only_number.findall(data))
                if number:
                    logging.info('The number extracted form: {0} is: {1}'.format(data, number))
            
                    nc.notify("Incomming call", "From: {0}".format(number))
            except KeyboardInterrupt:
                    logging.info('KeyboardInterrupt')
                    self.delete()
                    exit()


    def connect(self):
        fritzbox = self.fritzbox
        for i in range(3):
            try:
                self.telnet = Telnet(fritzbox, '1012', 60)
                logging.info('Telnet connection to {0} succseed'.format(fritzbox))
                break
            except:
                message = 'Telnet connection #{0} failed'.format(i)
                if i >= 3:
                    logging.Waiting(message)
                else:
                    logging.info(message)
        return 0

    def reconnect(self):
        self.telnet.close()
        self.connect()

    def delete(self):
        logging.info('Clearing Telnet session up')
        self.telnet.close()
开发者ID:philippmayrth,项目名称:call-monitor,代码行数:59,代码来源:call_monitor.py


注:本文中的telnetlib.Telnet类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。