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


Python Telnet.read_until方法代码示例

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


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

示例1: Player

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
class Player(Player):
    @classmethod
    def running(self):
        try:
            Telnet(lyvi.config['mpd_host'], lyvi.config['mpd_port']).close()
            return True
        except OSError:
            return False

    def __init__(self):
        """Get a path to the music directory and initialize the telnet connection."""
        self.music_dir = None
        if os.path.exists(lyvi.config['mpd_config_file']):
            for line in open(lyvi.config['mpd_config_file']):
                if line.strip().startswith('music_directory'):
                    self.music_dir = line.split('"')[1]
        self.telnet = Telnet(lyvi.config['mpd_host'], lyvi.config['mpd_port'])
        self.telnet.read_until(b'\n')

    def get_status(self):
        data = {'artist': None, 'album': None, 'title': None, 'file': None, 'length': None}

        self.telnet.write(b'status\n')
        response = self.telnet.read_until(b'OK').decode()
        self.telnet.write(b'currentsong\n')
        response += self.telnet.read_until(b'OK').decode()
        t = {
            'state: ': 'state',
            'Artist: ': 'artist',
            'Title: ': 'title',
            'Album: ': 'album',
            'file: ': 'file',
            'time: ': 'length',
        }
        for line in response.splitlines():
            for k in t:
                if line.startswith(k):
                    data[t[k]] = line.split(k, 1)[1]
                    break
        data['file'] = os.path.join(self.music_dir, data['file']) if data['file'] and self.music_dir else None
        data['length'] = int(data['length'].split(':')[1]) if data['length'] else None

        for k in data:
            setattr(self, k, data[k])

    def send_command(self, command):
        cmd = {
            'play': b'play\n',
            'pause': b'pause\n',
            'next': b'next\n',
            'prev': b'previous\n',
            'stop': b'stop\n',
        }.get(command)

        if cmd:
            self.telnet.write(cmd)
            return True
    
    def cleanup(self):
        self.telnet.close()
开发者ID:lejenome,项目名称:lyvi,代码行数:62,代码来源:mpd.py

示例2: __init__

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
    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,代码行数:32,代码来源:james.py

示例3: main

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
def main(host, port):
        telnet = Telnet()
        telnet.open(host, port)
	#Usually Telnet prompt starts with this, if the telnet service provide another
	#prompt, change it to that prompt
	telnet.read_until("login: ") 
	telnet.write(user + "\n")
	#the note above also applies for this
	telnet.read_until("Password: ")
	telnet.write(password + "\n")
	#just omit this line if you want to just have the telnet command prompt,
	#or change it to what feel confortable with
	telnet.write("shell\n")
        reader = ReaderThread(telnet)
        reader.start()

	fd = sys.stdin.fileno()
	old_settings = termios.tcgetattr(fd)
	tty.setraw(fd)
        while 1:
                if not reader.isAlive(): break
		ch = sys.stdin.read(1)
                telnet.write(ch)
        telnet.close()
	termios.tcsetattr(fd, 1, old_settings)
开发者ID:AlexxNica,项目名称:exploit-database,代码行数:27,代码来源:17670.py

示例4: tlnt_connect

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
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,代码行数:32,代码来源:ascft.py

示例5: TelnetConnect

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
class TelnetConnect(object):
    def __init__(self,ip_addr,username,password):
        self.ip_addr=ip_addr
        self.username=username
        self.password=password
        try: 
            self.remote_conn= Telnet(self.ip_addr, TELNET_PORT, TELNET_TIMEOUT)
        except soket.timeout:
            sys.exit("Timeout Connection")

    def login(self,sleep_time=1):
        output=self.remote_conn.read_until('sername:',TELNET_TIMEOUT)
        self.remote_conn.write(self.username +'\n')
        output+=self.remote_conn.read_until('assword:', TELNET_TIMEOUT)
        self.remote_conn.write(self.password+'\n')
        time.sleep(sleep_time)
        output+=self.remote_conn.read_very_eager()
        return output

    def send_command(self,cmd,sleep_time=1):
        cmd=cmd.rstrip()
        self.remote_conn.write(cmd + '\n')
        time.sleep(sleep_time)
        return self.remote_conn.read_very_eager()
    
    def close_conn(self):
        self.remote_conn.close()
开发者ID:munirmurad2165,项目名称:python-adv-course,代码行数:29,代码来源:testw2p3.py

示例6: ospf_telnet_open

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
def ospf_telnet_open():
 telnet_pointer=Telnet('127.0.0.1','2604')
 telnet_pointer.read_until("Password:")
 telnet_pointer.write("zebra\n")
 telnet_pointer.write("en\n")
 telnet_pointer.write("conf t\n")
 return telnet_pointer
开发者ID:parkjunhyo,项目名称:quagga_j,代码行数:9,代码来源:Q_telnetlib.py

示例7: initConnection

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
def initConnection(host, port, timeout):
    """initiate connection to PNA and returns Telnet object tn
    
    if connection is succesfull returns object tn
    """
    try:
        tn = Telnet(host, port, timeout)
        ans = tn.read_until("SCPI> ".encode(encoding='ascii', errors='strict'), timeout = 10).decode('ascii').strip()
        
        if debugCommunication:
            print(ans)
        else:
            pass
        
        tn.write("*IDN?".encode(encoding='ascii', errors='strict'))
        tn.write(termChar.encode(encoding='ascii', errors='strict'))   # just send ENTER to execute the command
        
        ans = tn.read_until("SCPI> ".encode(encoding='ascii', errors='strict'), timeout = 5).decode('ascii').strip()
        
        if debugCommunication:
            print(ans)
        else:
            pass   
        
        return tn
    
    except:
        print("Error while connecting.")
开发者ID:borisov-r,项目名称:EM3Dscanner,代码行数:30,代码来源:communication_PNA.py

示例8: __init__

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def __init__(self, endpoint, timeout):
     host, port = endpoint.split(':')
     elasticache_logger.debug('cluster: %s %s %s %s %s %s',
                              str(host), str(type(host)),
                              str(port), str(type(port)),
                              str(timeout), str(type(timeout)))
     tn = Telnet(host, port)
     tn.write('version\n')
     ret = tn.read_until('\r\n', timeout)
     elasticache_logger.debug('version: %s', ret)
     version_list = ret.split(' ')
     if len(version_list) != 2 or version_list[0] != 'VERSION':
         raise ElasticacheInvalidTelentReplyError(ret)
     version = version_list[1][0:-2]
     if StrictVersion(version) >= StrictVersion('1.4.14'):
         get_cluster = 'config get cluster\n'
     else:
         get_cluster = 'get AmazonElastiCache:cluster\n'
     tn.write(get_cluster)
     ret = tn.read_until('END\r\n',  timeout)
     elasticache_logger.debug('config: %s', ret)
     tn.close()
     p = re.compile(r'\r?\n')
     conf = p.split(ret)
     if len(conf) != 6 or conf[4][0:3] != 'END':
         raise ElasticacheInvalidTelentReplyError(ret)
     self.version = conf[1]
     self.servers = []
     nodes_str = conf[2].split(' ')
     for node_str in nodes_str:
         node_list = node_str.split('|')
         if len(node_list) != 3:
             raise ElasticacheInvalidTelentReplyError(ret)
         self.servers.append(node_list[1] + ':' + node_list[2])
开发者ID:root360,项目名称:elasticache_pyclient,代码行数:36,代码来源:memcache_client.py

示例9: update

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def update(self):
     tn = Telnet(self.host, self.port, self.timeout)
     tn.write(b'version\n')
     ret = tn.read_until(b'\r\n', self.timeout).decode('utf-8')
     logger.debug('version: %s', ret)
     version_list = ret.split(' ')
     if len(version_list) != 2 or version_list[0] != 'VERSION':
         raise ElasticacheInvalidTelentReplyError(ret)
     version = version_list[1][0:-2]
     if StrictVersion(version) >= StrictVersion('1.4.14'):
         get_cluster = b'config get cluster\n'
     else:
         get_cluster = b'get AmazonElastiCache:cluster\n'
     tn.write(get_cluster)
     ret = tn.read_until(b'END\r\n', self.timeout).decode('utf-8')
     logger.debug('config: %s', ret)
     tn.close()
     p = re.compile(r'\r?\n')
     conf = p.split(ret)
     if len(conf) != 6 or conf[4][0:3] != 'END':
         raise ElasticacheInvalidTelentReplyError(ret)
     version = int(conf[1])
     servers = []
     nodes_str = conf[2].split(' ')
     for node_str in nodes_str:
         node_list = node_str.split('|')
         if len(node_list) != 3:
             raise ElasticacheInvalidTelentReplyError(ret)
         servers.append(node_list[0] + ':' + node_list[2])
     with self.lock:
         if version > self.version:
             self.servers = servers
             self.version = version
             self.timestamp = time.time()
             logger.debug('cluster update: %s', self)
开发者ID:yupeng820921,项目名称:elasticache_pyclient,代码行数:37,代码来源:memcache_client.py

示例10: lineprofile

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def lineprofile(self, params):
     try:
         echo = params[18].split("_")
         print("Telnet " + params[6])
         tn = Telnet()
         tn.open(params[6], 23, self.telnetTimeout)
         
         if "9800" in params[1]: tn.write("\n")
         print(tn.read_until(echo[0], self.cmdTimeout))
         tn.read_until("\xff\xfc\x03", 1)
         
         for i in [1,2,3,4,5,7,9,10,8]:
             if params[i+7] <> "":
                 tn.write(params[i+7] + "\n")
                 if i == 9 and "HW" in params[1]: print(tn.read_until(": ", self.cmdTimeout)),
                 print(tn.read_until(echo[i], self.cmdTimeout)),
                 
         print("\n\nBDID: %s" % params[0])
         print("Equipment Type: %s (%s)" % (params[1], params[6]))
         print("L112 Port: %s" % params[5])
         print("Equipment Port: %s/%s/%s" % (params[2], params[3], params[4]))
     except:
         print("Execute command fail.")
     finally:
         tn.close()
开发者ID:flowsha,项目名称:zhwh,代码行数:27,代码来源:Port.py

示例11: changeTorIP

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def changeTorIP(self):
     tn = Telnet(self.serverIP, int(self.torControlPort))
     tn.write("AUTHENTICATE\r\n")
     tn.read_until("250 OK", 2)
     tn.write("signal NEWNYM\r\n")
     tn.read_until("250 OK", 2)
     tn.write("QUIT\r\n")
     tn.close()
开发者ID:nilesh-c,项目名称:jobinsights,代码行数:10,代码来源:LinkedinSpider.py

示例12: _makeRequest

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
    def _makeRequest(self, verb, **dikt):
        """Send a request to the server

        NOTE: does not validate the content of responses"""

        # Connect via telnet to the server
        connection = Telnet(self.host, self.port)

        # Receive the welcome message
        # Example: MaverickChessServer/1.0a1 WAITING_FOR_REQUEST
        welcome = connection.read_until("\r\n", MaverickClient.TIMEOUT)

        # Validate the welcome message
        err = None
        if welcome[:19] != "MaverickChessServer":
            err = "bad_name"
        elif welcome[19] != "/":
            err = "bad_header_separator"
        else:
            (version, sep, status) = welcome[20:].partition(" ")

            if version != __version__:
                err = "incompatible_version"
            elif sep != " ":
                err = "bad_separator"
            elif status != "WAITING_FOR_REQUEST\r\n":
                err = "bad_status"
        if err != None:
            MaverickClient._logger.error("Invalid server welcome (%s): %s",
                                         err, welcome)
            raise MaverickClientException("Invalid server welcome")

        # Send the request
        requestStr = "{0} {1}\r\n".format(verb,
                                          json.dumps(dikt,
                                                     encoding="utf-8"))
        connection.write(requestStr)

        # Receive the response
        response = connection.read_until("\n", MaverickClient.TIMEOUT)

        # Parse the response and deal with it accordingly
        statusString, _, value = response.partition(" ")
        if statusString == "SUCCESS":
            try:
                result = json.loads(value, object_hook=_asciify_json_dict)
            except ValueError:
                raise MaverickClientException("Invalid JSON in response")
            return result
        elif statusString == "ERROR":
            errMsg = value.rstrip()     # Trim trailing new line
            MaverickClient._logger.debug("Received error response: %s", errMsg)
            raise MaverickClientException(errMsg)
        else:
            msg = "Invalid status string received"
            MaverickClient._logger.error(msg)
            raise MaverickClientException(msg)
开发者ID:straxhaber,项目名称:maverick-chess,代码行数:59,代码来源:client.py

示例13: Login_to_device

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def Login_to_device(self):
    telnet_conn=Telnet(self.ip_addr,self.TELNET_PORT,self.TELNET_TIMEOUT)
    telnet_conn.read_until('sername:')
    telnet_conn.write(self.username + '\n')
    telnet_conn.read_until('assword:')
    telnet_conn.write(self.password + '\n')
    time.sleep(1)
    output=telnet_conn.read_very_eager()
    return  telnet_conn,output
开发者ID:karimjamali,项目名称:Course_Functions,代码行数:11,代码来源:course_functions.py

示例14: createNewConn

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
 def createNewConn(self):
     '''
     Connects to a digiport device and logs in
     '''
     portObj = Telnet(self.ip)
     portObj.read_until("login: ")
     portObj.write(self.userName + "\n")
     portObj.write(self.password + "\n")  
     return portObj
开发者ID:pyridoxus,项目名称:lab-tools,代码行数:11,代码来源:digiport.py

示例15: onJoin

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_until [as 别名]
	def onJoin(self, details):

		namespace = self.app_config['namespace']
		do_raw = self.app_config['raw'].lower()=='true'

		firebase_server = firebase.FirebaseApplication('https://amber-fire-3917.firebaseio.com')

		def send(key,d):
			return self.publish(namespace+u'.queue.'+key,d) and 1 or 0

		def blink(d):
			return send('blink',d['blinkStrength'])

		def data(d):
			return send('data',
				[d['eSense']['attention']
				,d['eSense']['meditation']
				,d['eegPower']['lowAlpha']
				,d['eegPower']['highAlpha']
				,d['eegPower']['lowBeta']
				,d['eegPower']['highBeta']
				,d['eegPower']['lowGamma']
				,d['eegPower']['highGamma']
				,d['eegPower']['delta']
				,d['eegPower']['theta']
				])

		def raw(d):
			return send('raw',d['rawEeg'])

		def sendany(d):
			print(d)
			if 'blinkStrength' in d:
				return blink(d)
			if 'eegPower' in d:
				return data(d)
			if 'rawEeg' in d:
				return raw(d)
			return None

		if self.app_config['debug'].lower()=='true':
			print('debug mode.')
			counter = 0
			while True:
				send('debug', counter)
				#print("Published event.")
				counter += 1
				yield sleep(1)
		else:
			tn = Telnet('localhost',13854)
			tn.write('{"enableRawOutput": %s, "format": "Json"}' % (['false','true'][do_raw],))
			i = tn.read_until('\r')
			while True:
				# ret = sendany(json.loads(tn.read_until('\r')))
				firebase_server.post('/mindwave', json.loads(tn.read_until('\r')))
				yield sleep(0.001)
开发者ID:khanh2907,项目名称:mind_watch,代码行数:58,代码来源:server_firebase.py


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