本文整理汇总了Python中telnetlib.Telnet.read_eager方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.read_eager方法的具体用法?Python Telnet.read_eager怎么用?Python Telnet.read_eager使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telnetlib.Telnet
的用法示例。
在下文中一共展示了Telnet.read_eager方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rifidi_server
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
def test_rifidi_server(self):
self.port = '2020'
self.host = 'localhost'
telnet = Telnet(self.host, self.port)
#telnet.write('\r\n')
#expected = '\r\nosgi> '
actual = telnet.read_eager()
#self.assertEqual(expected, actual)
expected = {}
expected['Rifidi App: Diagnostic:GPIO (STOPPED)'] = False
expected['Rifidi App: Diagnostic:Serial (STOPPED)'] = False
expected['Rifidi App: Diagnostic:Tags (STARTED)'] = False
expected['Rifidi App: Diagnostic:TagGenerator (STARTED)'] = False
expected['Rifidi App: AppService:ReadZones (STARTED)'] = False
expected['Rifidi App: AppService:SensorStatus (STARTED)'] = False
expected['Rifidi App: AppService:UniqueTagInterval (STARTED)'] = False
expected['Rifidi App: AppService:StableSet (STARTED)'] = False
expected['Rifidi App: AppService:UniqueTagBatchInterval (STARTED)'] = False
expected['Rifidi App: Monitoring:ReadZones (STARTED)'] = False
expected['Rifidi App: Monitoring:Tags (STARTED)'] = False
expected['Rifidi App: Monitoring:SensorStatus (STARTED)'] = False
expected['Rifidi App: Ambient:Association (STARTED)'] = False
expected['Rifidi App: Ambient:DBApp (STARTED)'] = False
expected['Rifidi App: Ambient:MessageReceiver (STARTED)'] = False
expected['Rifidi App: Ambient:SensorDownAlert (STARTED)'] = False
expected['Rifidi App: Ambient:TagCountApp (STARTED)'] = False
expected['Rifidi App: Ambient:StationStatusAlert (STARTED)'] = False
expected['Rifidi App: Ambient:Grouping (STARTED)'] = False
expected['Rifidi App: Ambient:TagReadApp (STARTED)'] = False
expected['Rifidi App: Ambient:Receiving (STARTED)'] = False
expected['Rifidi App: Ambient:Portal (STOPPED)'] = False
expected['Rifidi App: Ambient:ReceiveTest (STARTED)'] = False
telnet.write('apps\r\n')
time.sleep(2.5)
done = False
while not done:
value = ''
value = telnet.read_eager()
actual += value
if value == '':
done = True
actual = actual.replace('osgi>', '')
actual = re.sub(r'[0-9]+:', '', actual, count=0)
actual = actual.split('\r\n')
for i in range(0, actual.__len__()-1):
actual[i] = re.sub(r'^ ', '', actual[i])
for i in actual:
if i in expected:
expected[i] = True
for i in expected.keys():
self.assertTrue(i)
示例2: test_rifidi_server
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
def test_rifidi_server(self):
ret = subprocess.call(['sudo', '/etc/init.d/rifidi-server', 'stop'])
ret1 = subprocess.call(['sudo', '/etc/init.d/rifidi-server', 'start'])
assert not ret and not ret1
self.port = '2020'
self.host = 'localhost'
telnet = Telnet(self.host, self.port)
#telnet.write('\r\n')
expected = '\r\nosgi> '
actual = telnet.read_eager()
self.assertEqual(expected, actual)
expected = '\r\nosgi> 0:Rifidi App: Diagnostic:GPIO (STOPPED)\r\n'+\
'1:Rifidi App: Diagnostic:Serial (STOPPED)\r\n'+\
'2:Rifidi App: Diagnostic:Tags (STARTED)\r\n'+\
'3:Rifidi App: Diagnostic:TagGenerator (STARTED)\r\n'+\
'4:Rifidi App: AppService:ReadZones (STARTED)\r\n'+\
'5:Rifidi App: AppService:SensorStatus (STARTED)\r\n'+\
'6:Rifidi App: AppService:UniqueTagInterval (STARTED)\r\n'+\
'7:Rifidi App: AppService:StableSet (STARTED)\r\n'+\
'8:Rifidi App: AppService:UniqueTagBatchInterval (STARTED)\r\n'+\
'9:Rifidi App: Monitoring:ReadZones (STARTED)\r\n'+\
'10:Rifidi App: Monitoring:Tags (STARTED)\r\n'+\
'11:Rifidi App: Monitoring:SensorStatus (STARTED)\r\n'+\
'osgi> '
telnet.write('apps\r\n')
time.sleep(2.5)
done = False
while not done:
value = ''
value = telnet.read_eager()
actual += value
if value == '':
done = True
self.assertEqual(expected, actual)
示例3: telnetspawn
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
class telnetspawn(pexpect.spawn):
closed = True
readahead = 16
readahead_buf = ''
def __init__ (self, host, port=23, timeout=30, maxread=2000,
searchwindowsize=None, logfile=None, sendlinesep="\r\n"):
self.telnet = Telnet(host, port)
self.sendlinesep = sendlinesep
self.args = None
self.command = None
pexpect.spawn.__init__(self, None, None, timeout, maxread,
searchwindowsize, logfile)
self.child_fd = -1
self.own_fd = False
self.closed = False
self.name = '<telnet connection %s:%d>'%(host, port)
self.default_timeout = timeout
return
def __del__ (self):
telnetspawn.close(self)
self.logfile.write("\n")
return
def close (self):
if self.closed:
return
self.telnet.close()
self.closed = True
return
def flush (self):
while len(self.telnet.read_eager()) > 0:
continue
return
def isatty (self):
return False
def isalive (self):
return not self.closed
def terminate (self, force=False):
raise ExceptionPexpect ('This method is not valid for telnet connections.')
def kill (self, sig):
return
def send(self, s):
time.sleep(self.delaybeforesend)
if self.logfile is not None:
self.logfile.write (s)
self.logfile.flush()
if self.logfile_send is not None:
self.logfile_send.write (s)
self.logfile_send.flush()
self.telnet.write(s)
return s
def send(self, s, noSendLog=None):
if noSendLog is not None:
self.send(s)
else:
time.sleep(self.delaybeforesend)
self.telnet.write(s)
return s
def read_nonblocking (self, size=1, timeout=-1):
if timeout != -1:
self.timeout = timeout
buf = self.readahead_buf
self.readahead_buf = ''
# FIXME: update timeout during this loop!!
more = self.telnet.read_eager()
while len(more) > 0:
buf += more
more = self.telnet.read_eager()
if len(buf) <= size:
if self.logfile is not None:
self.logfile.write(buf)
#.........这里部分代码省略.........
示例4: Telnet
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
import os
import sys
import re
import time
import signal
from os.path import join
import subprocess
from subprocess import Popen, PIPE
from telnetlib import Telnet
if __name__ == '__main__':
# try a nice shutdown
try :
telnet = Telnet('localhost', '2020')
actual = telnet.read_eager()
telnet.write('close\r\n')
time.sleep(1)
actual = telnet.read_eager()
telnet.write('y\r\n')
except:
pass
# kill anything that is left
p1 = Popen(['ps','ax'], stdout=PIPE)
p2 = Popen(['grep', 'org.rifidi.edge'], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
output = output.split('\n')
if output:
for i in output:
if re.search('grep', i):
示例5: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
class Stream:
def __init__(self, host, port, timeout=3000, testing=False):
self.host = host
self.port = port
self.timeout = timeout
self.socket = None
self.testing = testing
self.state = ConnectionState.INIT
def connect(self):
if self.testing:
logger.debug("Connected")
self.state = ConnectionState.CONNECTED
return
if self.state not in [ConnectionState.INIT or
ConnectionState.DISCONNECTED]:
return
try:
self.socket = Telnet(self.host, self.port, self.timeout)
data = self.socket.read_until(str.encode("*"))
self.state = ConnectionState.CONNECTED
logger.info(data)
except OSError:
logger.critical("Socket connection error")
@property
def is_connected(self):
return self.state == ConnectionState.CONNECTED
def ensure_connection(self):
if self.is_connected:
return
raise OSError
def close(self):
if self.testing:
logger.debug("Closed")
return
if not self.is_connected:
return
self.state = ConnectionState.DISCONNECTED
self.socket.close()
def send(self, cmd):
logger.debug(cmd)
if self.testing:
return
self.ensure_connection()
try:
self.socket.write(cmd.encode("ascii") + b'\n')
except OSError:
logger.error("Error sending data")
def read(self):
self.ensure_connection()
while True:
data = self.socket.read_eager()
if len(data) == 0:
break
yield data
def read_until(self, string):
if self.testing:
logger.debug("Reading")
return
self.ensure_connection()
return self.socket.read_until(str.encode(string))
示例6: TelnetClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
class TelnetClient():
def __init__(self, port, password, server_id):
self.terminate = False
self.server_id = server_id
self.tn = Telnet('localhost', port)
self.tn.read_until('Enter password:{0}'.format(os.linesep))
self.tn.write(password + os.linesep)
self.start_time = time.time()
self.run()
def read(self):
try:
return self.tn.read_eager()
except:
self.terminate = True
return ''
def write(self, line):
try:
self.tn.write(line.encode('UTF-8') + os.linesep)
except:
self.terminate = True
def send_back(self, lines_to_send):
key = 'server-{0}-out'.format(self.server_id)
lines = cache.get(key, [])
lines.extend(lines_to_send)
cache.set(key, lines)
def get_lines_from_cache(self):
key = 'server-{0}-in'.format(self.server_id)
lines = cache.get(key, [])
cache.delete(key)
return lines
def ping(self):
pingtime = cache.get('server-{0}-ping'.format(self.server_id))
if not pingtime or time.time() - pingtime > 3:
self.terminate = True
def run(self):
received_data = ''
while True:
# check if we should shut down the process
self.ping()
# terminate!!
if self.terminate:
break
# receive lines from server
received_data += self.read()
lines = received_data.split(os.linesep)
received_data = lines.pop() # put tail back to buffer for next run
# lines to send back to client
if lines:
self.send_back(lines)
# lines to send to telnet server
for line in self.get_lines_from_cache():
self.write(line)
time.sleep(0.2) # be nice to CPU run only 5 times per sec
示例7: TelnetClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
class TelnetClient(object):
#----------------------------------------------------------------------
def __init__(self, host, port):
self._client = Telnet(host, port, timeout=TELNET_TIMEOUT)
self._prompts = dict(default='>>> ', continous='... ')
self._prompt_default = self._prompts['default']
self._prompt_continous = self._prompts['continous']
self._next_prompt = self._prompts['default']
#----------------------------------------------------------------------
def _read_input(self):
prompt = self._next_prompt if sys.stdin.isatty() else ''
data_to_send = str(raw_input(prompt))
data_to_send += '\n'
return data_to_send
#----------------------------------------------------------------------
def _read_response(self):
return self._client.read_eager()
#----------------------------------------------------------------------
def _get_next_prompt(self, response):
current_prompt = response[-4:]
if current_prompt in self._prompts.itervalues():
self._next_prompt = current_prompt
else:
self._next_prompt = None
#----------------------------------------------------------------------
def _have_prompt(self):
return (self._next_prompt is not None)
#----------------------------------------------------------------------
def _fetch_remote_locals(self):
"""
Read the locals() from the remote console and then add their keys
into the local main namespace to get them auto completed as they were
'real' locals.
"""
self._client.write('locals().keys()\n')
received_data = self._client.read_until(self._prompt_default, timeout=TELNET_TIMEOUT)
received_data = received_data[:-4]
keys = eval(received_data)
for key in keys:
if not __main__.__dict__.has_key(key):
__main__.__dict__[key] = getattr(__main__, key, None)
#----------------------------------------------------------------------
def _get_initial_prompt(self):
received_data = self._client.read_until(self._prompt_default, timeout=TELNET_TIMEOUT)
if sys.stdin.isatty():
sys.stdout.write(received_data[:-4])
# do some magic for auto completion
self._fetch_remote_locals()
# enable readline completion after we filled __main__.__dict__ with the
# locals of the remote console
readline.parse_and_bind("tab: complete")
#----------------------------------------------------------------------
def _run(self):
self._get_initial_prompt()
while True:
if self._have_prompt():
data_to_send = self._read_input()
if data_to_send:
self._client.write(data_to_send)
received_data = self._read_response()
self._get_next_prompt(received_data)
if self._next_prompt:
# cut off the prompt, if any
received_data = received_data[:-4]
# print data
sys.stdout.write(received_data)
#----------------------------------------------------------------------
def run(self):
try:
return self._run()
except (EOFError, KeyboardInterrupt):
pass
finally:
self._client.close()
示例8: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
#.........这里部分代码省略.........
_, match, _ = self.conn.expect(
["RX: ZDO, command 0x[0-9A-Za-z]{4}, status: 0x([0-9A-Za-z]{2})"], timeout=timeout)
if match is None:
raise AssertionError("TIMED OUT waiting for bind response")
if match.group(1) != '00':
raise AssertionError("Bind Request returned status %s" % match.group(1))
def configure_reporting(self, destination, attribute, min_interval, max_interval, threshold):
'''
Configures the device to report the given attribute to the controller.
'''
if attribute.type in ['INT8U', 'INT16U', 'INT32U', 'INT8S', 'INT16S', 'INT32S']:
threshold_value_list = _list_from_arg(attribute.type, threshold)
else:
threshold_value_list = [0]
self.write('zcl global send-me-a-report %d %d %d %d %d {%s}' % (
attribute.cluster_code, attribute.code, attribute.type_code,
min_interval, max_interval, _hex_string_from_list(threshold_value_list)))
self.write('send 0x%04X 1 1' % destination)
def write_attribute(self, destination, attribute, value, timeout = 10):
'''
Writes an attribute on a device. Attributes are instances of
ZCLAttribute.
'''
payload = _list_from_arg(attribute.type, value, strip_string_length=True)
write_log(0, "Writing Attribute %s to %s" % (attribute.name,
" ".join(['%02X' % x for x in payload])))
self.write('zcl global write %d %d %d {%s}' %
(attribute.cluster_code, attribute.code, attribute.type_code,
" ".join(['%02X' % x for x in payload])))
self.write('send 0x%04X 1 1' % destination)
#RX len 4, ep 01, clus 0x0020 (Unknown clus. [0x0020]) FC 18 seq EC cmd 04 payload[00 ]
_, match, _ = self.conn.expect(['RX len [0-9]+, ep [0-9A-Z]+, ' +
'clus 0x%04X \([a-zA-Z0-9\.\[\]\(\) ]+\) .* cmd 04 payload\[([0-9A-Z ]*)\]' % attribute.cluster_code],
timeout=timeout)
#TODO: actually do something with the response
def write_local_attribute(self, attribute, value):
'''
Writes an attribute that's local to the controller.
'''
payload = _list_from_arg(attribute.type, value)
payload_string = " ".join(['%02X' % x for x in payload])
self.write('write 1 %d %d 1 %d {%s}' % (
attribute.cluster_code, attribute.code, attribute.type_code,
payload_string))
time.sleep(1)
def make_server(self):
self.write('zcl global direction 1')
def make_client(self):
self.write('zcl global direction 0')
#T000BD5C5:RX len 11, ep 01, clus 0x000A (Time) FC 18 seq 20 cmd 01 payload[00 00 00 E2 00 00 00 00 ]
#READ_ATTR_RESP: (Time)
#- attr:0000, status:00
#type:E2, val:00000000
def read_attribute(self, destination, attribute, timeout=10):
self.write('zcl global read %d %d' %
(attribute.cluster_code, attribute.code))
self.write('send 0x%04X 1 1' % destination)
_, match, _ = self.conn.expect(['RX len [0-9]+, ep [0-9A-Z]+, ' +
'clus 0x%04X \([a-zA-Z0-9\.\[\]\(\) ]+\) .* cmd 01 payload\[([0-9A-Z ]*)\]' % attribute.cluster_code],
timeout=timeout)
if match is None:
raise AssertionError('TIMED OUT reading attribute %s' % attribute.name)
payload = [int(x, 16) for x in match.group(1).split()]
attribute_id = _pop_argument('INT16U', payload)
status = _pop_argument('INT8U', payload)
if status != 0:
raise AssertionError('Attribute Read failed with status 0x%02X' % status)
attribute_type_code = _pop_argument('INT8U', payload)
attribute_type = zcl.get_type_string(attribute_type_code)
return _pop_argument(attribute_type, payload)
#T183FCD64:RX len 5, ep 01, clus 0x0020 (Unknown clus. [0x0020]) FC 18 seq D3 cmd 0B payload[03 00 ]
def expect_zcl_command(self, command, timeout=10):
'''
Waits for an incomming message and validates it against the given
cluster ID, command ID, and arguments. Any arguments given as None
are ignored. Raises an AssertionError on mis-match or timeout.
'''
# read and discard any data already queued up in the buffer
self.conn.read_eager()
# we're pretty loose about what we accept as the incoming command. This is
# mostly to more easily handle DefaultResponses, which are displayed
# with their cluster ID as whatever cluster they're responding to
_, match, _ = self.conn.expect(['RX .* cmd %02X payload\[([0-9A-Z ]*)\]'
% command.code], timeout=timeout)
if match is None:
raise AssertionError("TIMED OUT waiting for " + command.name)
payload = [int(x, 16) for x in match.group(1).split()]
_validate_payload(command.args, payload)
def write(self, msg):
self.conn.write(msg + '\n')
示例9: while
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import read_eager [as 别名]
try:
while (rescnt<2):
#print ("aaa")
if (songlen>titleDispLen):
MoveTime+=1
if (MoveTime>MoveRate):
MoveTime=0
if (DisplayPos+titleDispLen>songlen):
DisplayPos=0
else:
DisplayPos+=2
cad.lcd.set_cursor(0,0)
dispEnd=DisplayPos+titleDispLen
write_to_cad(title[DisplayPos:dispEnd])
try:
readline=conn.read_eager()
except:
sys.exit()
if (len(readline) >0 ):
LineEnd=readline.find(b'\n')
if LineEnd == -1:
fullLine+=readline.decode('utf8')
if LineEnd == 0:
fullLine=parse.unquote(fullLine)
#print (fullLine)
displayline(fullLine)
readline=readline[2:len(readline)]
fullLine=readline.decode('utf8')