本文整理汇总了Python中telnetlib.Telnet.set_option_negotiation_callback方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.set_option_negotiation_callback方法的具体用法?Python Telnet.set_option_negotiation_callback怎么用?Python Telnet.set_option_negotiation_callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telnetlib.Telnet
的用法示例。
在下文中一共展示了Telnet.set_option_negotiation_callback方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
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)
示例2: _getCellAlarm
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
def _getCellAlarm(self):
'''Get CDMA alarms from omp server by telnet.
'''
alarms = ""
tn = Telnet()
try:
#tn.set_debuglevel(1)
tn.open(self.fwHost, self.fwPort, 10)
tn.set_option_negotiation_callback(self._process_iac)
tn.read_until("Login: ", 5)
tn.write(self.fwUser + "\r\n")
tn.read_until("Password: ", 5)
tn.write(self.fwPasswd + "\r\n")
tn.read_until("Please select the resource : ", 5)
tn.set_option_negotiation_callback(None)
tn.write("1\n")
tn.read_until("login: ", 5)
tn.write(self.ompUser + "\n")
tn.read_until("Password: ", 5)
tn.write(self.ompPasswd + "\n")
result = tn.read_until("> ", 5)
if "New Password:" in result:
passwd = self._getRandomPassword()
tn.write(passwd + "\n")
tn.read_until(": ", 5)
tn.write(passwd + "\n")
tn.read_until("> ", 5)
self.ompOldPasswd = self.ompPasswd
self.ompPasswd = passwd
self.config.set("omp", "omp_passwd", self.ompPasswd)
self.config.set("omp", "omp_passwd_old", self.ompOldPasswd)
fp = open(self.confile, "r+")
self.config.write(fp)
fp.close()
self._writelog("change new password successfully.")
elif "Login incorrect" in result:
self._reloadPassword()
return alarms
tn.write("TICLI\n")
tn.read_until("> ", 5)
tn.write("op:alarm 13\n")
alarms = tn.read_until("COMPLETE", 5)
tn.close()
except:
tn.close()
self._writelog("get CDMA alarms fail.")
finally:
tn.close()
return alarms
示例3: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
def main(hostname, username, password):
t = Telnet(hostname)
# t.set_debuglevel(1) # uncomment to get debug messages
t.set_option_negotiation_callback(process_option)
t.read_until(b'login:', 10)
t.write(username.encode('utf-8') + b'\r')
t.read_until(b'assword:', 10) # first letter might be 'p' or 'P'
t.write(password.encode('utf-8') + b'\r')
n, match, previous_text = t.expect([br'Login incorrect', br'\$'], 10)
if n == 0:
print("Username and password failed - giving up")
else:
t.write(b'exec echo My terminal type is $TERM\n')
print(t.read_all().decode('ascii'))
示例4: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
def main():
tn = None
outcome = None
try:
# Ensure there are no paralell runs of this script
lock.acquire(timeout=5)
# Connect and authenticate
tn = Telnet(jcli["host"], jcli["port"])
tn.set_option_negotiation_callback(process_option)
# for telnet session debug:
# tn.set_debuglevel(1000)
tn.read_until("Authentication required", 16)
tn.write("\r\n")
tn.read_until("Username:", 16)
tn.write(jcli["username"] + "\r\n")
tn.read_until("Password:", 16)
tn.write(jcli["password"] + "\r\n")
# We must be connected
idx, obj, response = tn.expect([r"Welcome to Jasmin ([0-9a-z\.]+) console"], 16)
if idx == -1:
raise jCliSessionError("Authentication failure")
# Wait for prompt
wait_for_prompt(tn)
# Build outcome for requested key
if args.d == "smppcs":
response = wait_for_prompt(tn, command="stats --smppcs\r\n")
smppcs = get_list_ids(response)
outcome = {"data": []}
for cid in smppcs:
outcome["data"].append({"{#CID}": cid})
elif args.d == "users":
response = wait_for_prompt(tn, command="stats --users\r\n")
users = get_list_ids(response)
outcome = {"data": []}
for uid in users:
outcome["data"].append({"{#UID}": uid})
except LockTimeout:
print "Lock not acquired, exiting"
except AlreadyLocked:
print "Already locked, exiting"
except Exception, e:
print type(e)
print "Error: %s" % e
示例5: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
def main():
tn = None
outcome = None
try:
# Ensure there are no paralell runs of this script
lock.acquire(timeout=5)
# Connect and authenticate
tn = Telnet(jcli['host'], jcli['port'])
tn.set_option_negotiation_callback(process_option)
# for telnet session debug:
#tn.set_debuglevel(1000)
tn.read_until('Authentication required', 16)
tn.write("\r\n")
tn.read_until("Username:", 16)
tn.write(jcli['username']+"\r\n")
tn.read_until("Password:", 16)
tn.write(jcli['password']+"\r\n")
# We must be connected
idx, obj, response = tn.expect([r'Welcome to Jasmin (\d+\.\d+[a-z]+\d+) console'], 16)
if idx == -1:
raise jCliSessionError('Authentication failure')
# Wait for prompt
wait_for_prompt(tn)
# Build outcome for requested key
if args.d == 'smppcs':
response = wait_for_prompt(tn, command = "stats --smppcs\r\n")
smppcs = get_list_ids(response)
outcome = {'data': []}
for cid in smppcs:
outcome['data'].append({'{#CID}': cid})
elif args.d == 'users':
response = wait_for_prompt(tn, command = "stats --users\r\n")
users = get_list_ids(response)
outcome = {'data': []}
for uid in users:
outcome['data'].append({'{#UID}': uid})
except LockTimeout:
print 'Lock not acquired, exiting'
except AlreadyLocked:
print 'Already locked, exiting'
except Exception, e:
print type(e)
print 'Error: %s' % e
示例6: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
def main():
tn = None
try:
# Ensure there are no paralell runs of this script
lock.acquire(timeout=5)
# Connect and authenticate
tn = Telnet(jcli['host'], jcli['port'])
# for telnet session debug:
#tn.set_debuglevel(1000)
tn.set_option_negotiation_callback(process_option)
tn.read_until('Authentication required', 16)
tn.write("\r\n")
tn.read_until("Username:", 16)
tn.write(jcli['username']+"\r\n")
tn.read_until("Password:", 16)
tn.write(jcli['password']+"\r\n")
# We must be connected
idx, obj, response = tn.expect([r'Welcome to Jasmin (\d+\.\w+) console'], 16)
if idx == -1:
raise jCliSessionError('Authentication failure')
version = obj.group(1)
# Wait for prompt
wait_for_prompt(tn)
# Build outcome for requested key
metrics = []
for key in keys:
if key == 'version':
metrics.append(Metric(jcli['host'], 'jasmin[%s]' % key, version))
elif type(key) == dict and 'smppsapi' in key:
response = wait_for_prompt(tn, command = "stats --smppsapi\r\n")
for k in key['smppsapi']:
metrics.append(Metric(jcli['host'], 'jasmin[smppsapi.%s]' % k, get_stats_value(response, k)))
elif type(key) == dict and 'httpapi' in key:
response = wait_for_prompt(tn, command = "stats --httpapi\r\n")
for k in key['httpapi']:
metrics.append(Metric(jcli['host'], 'jasmin[httpapi.%s]' % k, get_stats_value(response, k)))
elif type(key) == dict and 'smppcs' in key:
# Get stats from statsm
response = wait_for_prompt(tn, command = "stats --smppcs\r\n")
smppcs = get_list_ids(response)
# Get statuses from smppccm
response = wait_for_prompt(tn, command = "smppccm -l\r\n")
smppcs_status = get_smppcs_service_and_session(response)
# Build outcome
for cid in smppcs:
# From stats
response = wait_for_prompt(tn, command = "stats --smppc %s\r\n" % cid)
for k in key['smppcs']:
metrics.append(Metric(jcli['host'], 'jasmin[smppc.%s,%s]' % (k, cid), get_stats_value(response, k)))
# From smppccm
metrics.append(Metric(jcli['host'], 'jasmin[smppc.service,%s]' % (cid), smppcs_status[cid]['service']))
metrics.append(Metric(jcli['host'], 'jasmin[smppc.session,%s]' % (cid), smppcs_status[cid]['session']))
elif type(key) == dict and 'users' in key:
response = wait_for_prompt(tn, command = "stats --users\r\n")
users = get_list_ids(response)
for uid in users:
response = wait_for_prompt(tn, command = "stats --user %s\r\n" % uid)
for k in key['users']['httpapi']:
metrics.append(Metric(jcli['host'], 'jasmin[user.httpapi.%s,%s]' % (k, uid), get_stats_value(response, k, stat_type = 'HTTP Api')))
for k in key['users']['smppsapi']:
if k in ['bound_rx_count', 'bound_tx_count', 'bound_trx_count']:
r = get_stats_value(response, key = 'bound_connections_count', stat_type = 'SMPP Server')
r = json.loads(r.replace("'", '"'))
if k == 'bound_rx_count':
v = r['bind_receiver']
elif k == 'bound_tx_count':
v = r['bind_transmitter']
elif k == 'bound_trx_count':
v = r['bind_transceiver']
else:
v = get_stats_value(response, k, stat_type = 'SMPP Server')
metrics.append(Metric(jcli['host'], 'jasmin[user.smppsapi.%s,%s]' % (k, uid), v))
#print metrics
# Send packet to zabbix
send_to_zabbix(metrics, zabbix_host, zabbix_port)
except LockTimeout:
print 'Lock not acquired, exiting'
except AlreadyLocked:
print 'Already locked, exiting'
except Exception, e:
print type(e)
print 'Error: %s' % e
示例7: process_option
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
# How your code might look if you intercept Telnet options yourself
from telnetlib import Telnet, IAC, DO, DONT, WILL, WONT, SB, SE, TTYPE
def process_option(tsocket, command, option):
if command == DO and option == TTYPE:
tsocket.sendall(IAC + WILL + TTYPE)
print('Sending terminal type "mypython"')
tsocket.sendall(IAC + SB + TTYPE + b'\0' + b'mypython' + IAC + SE)
elif command in (DO, DONT):
print('Will not', ord(option))
tsocket.sendall(IAC + WONT + option)
elif command in (WILL, WONT):
print('Do not', ord(option))
tsocket.sendall(IAC + DONT + option)
t = Telnet('localhost')
# t.set_debuglevel(1) # uncomment this for debugging messages
t.set_option_negotiation_callback(process_option)
t.read_until(b'login:', 5)
t.write(b'brandon\n')
t.read_until(b'assword:', 5) # so P can be capitalized or not
t.write(b'mypass\n')
n, match, previous_text = t.expect([br'Login incorrect', br'\$'], 10)
if n == 0:
print("Username and password failed - giving up")
else:
t.write(b'exec echo My terminal type is $TERM\n')
print(t.read_all().decode('ascii'))
示例8: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
class Main:
def __init__(self):
self.connected = False
self.logged_in = False
self.negotiating = False
self.utf8 = codecs.lookup('utf-8')
self.blink = False
self.cur_len = 0
self.pw = False
self.root = tkinter.Tk()
self.root.title('BIXpy')
self.Text = StringVar()
self.init_widgets()
self.root.protocol("WM_DELETE_WINDOW", self.cancel)
self.prog = ProgramOptions()
self.prog.read('ProgramOptions')
geom = self.prog.Main_Geometry.Value
if geom:
self.root.geometry(geom)
self.root.bind("<Return>", self.send_text)
self.root.initial_focus = self.entry
self.root.initial_focus.focus_set()
self.user = UserOptions()
self.user.read('UserOptions')
self.telnet = None
self.wrap_chars = ' ,;:/\\]})=-+\n'
self.root.mainloop()
def init_widgets(self):
self.options = ttk.Button(self.root, command=self.options, text="Options", width=12)
self.options.grid(column=0, row=0, sticky='w')
self.conn = ttk.Button(self.root, command=self.connect, text='Connect', width=12)
self.disc = ttk.Button(self.root, command=self.disconnect, text='Disconnect', width=12)
self.conn.grid(column=1, row=0, sticky='w')
self.entry = ttk.Entry(self.root, textvariable = self.Text, width=90)
self.entry.grid(column=2, row=0, sticky='ew')
self.txt = tkinter.Text(self.root, width=80, height=50)
self.txt.config(state = tkinter.DISABLED)
self.txt.grid(column=0, row=1, columnspan=3, sticky='nwes')
self.txt.bind('<Button-1>', self.single_click)
self.txt.bind('<Double-1>', self.double_click)
self.txt.bind_all('<<Selection>>', self.launch_web)
sb = ttk.Scrollbar(command=self.txt.yview, orient='vertical')
sb.grid(column=3, row=1, sticky='ns')
self.txt['yscrollcommand'] = sb.set
self.root.grid_columnconfigure(2, weight=1)
self.root.grid_rowconfigure(1, weight=1)
def cancel(self, event = None):
self.disconnect()
if self.root.state() == 'normal':
geom = self.root.geometry()
self.prog.Main_Geometry.Value = geom
self.prog.write('ProgramOptions')
self.root.destroy()
def connect(self):
if not self.connected:
self.append('\nConnecting...')
self.root.update()
if self.telnet:
self.telnet.close()
host = self.user.Host_Name.Value
if not host:
host = 'nlzero.com'
self.telnet = Telnet(host, 23, 60)
self.telnet.set_option_negotiation_callback(self.telnet_negotiation)
self.append('\nConnected.\n')
self.disc.grid(column=1, row=0, sticky='w')
self.conn.grid_forget()
self.connected = True
self.root.update()
self.process_telnet()
def single_click(self, event):
self.d_click = False
def double_click(self, event):
self.d_click = True
def launch_web(self, event):
if self.d_click:
try:
text = event.widget.get('sel.first', 'sel.last')
except:
text = None
print(text)
if text:
webbrowser.open(text)
def send_text(self, event = None):
if self.telnet and self.connected:
line = self.Text.get().replace('\r\n', '\n').replace('\n\r', '\n').replace('\r', '\n')
org_len = len(line) + self.cur_len
first_time = True
while first_time or len(line) > 0:
first_time = False
if len(line) + self.cur_len > 72:
idx = 72 - self.cur_len
while idx > 0 and ((not line[idx] in self.wrap_chars) or \
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
class BrcmFirmwareDump:
def __init__(self, ip, user, password, port=23):
# Connect
self.tn = Telnet(ip,port,TIMEOUT)
# self.tn.set_debuglevel(1)
# workarround to avoid the connection getting stuck at option negociation
self.tn.set_option_negotiation_callback(self.option_negociation)
# Some old broadcom versions need any character
# being send before prompting for the username
while True:
r = self.tn.read_until("ogin: ", TIMEOUT)
if re.search("ogin:", r):
break
# Send a '\n'
self.tn.write("\n")
# Send the username
self.tn.write(user+"\n")
# Send the password
self.tn.read_until("assword: ")
self.tn.write(password+"\n")
# Get the first prompt
r = self.tn.read_until("> ")
# Log in as root if necessary
if re.search("Console", r):
self.tn.write("su\n")
self.tn.read_until("assword: () []")
self.tn.write("brcm\n")
self.tn.read_until("> ")
self.tn.write("\n")
self.tn.read_until("> ")
self.tn.write("cd flash\n")
self.tn.read_until("\r\n\r\nCM/Flash> ")
'''
self.tn.write("deinit\n")
self.tn.read_until("\r\n\r\nCM/Flash> ")
self.tn.write("init\n")
self.tn.read_until("\r\n\r\nCM/Flash> ")
'''
def log(self, message, image=1):
print "Image%d> %s" % (image, message)
def option_negociation(self, socket, command, option):
pass
def read_block(self, image, block):
# Get a read command valid response
while True:
offset = block*BLOCK_SIZE
command = "read 4 %d %d" % (BLOCK_SIZE,offset)
self.tn.write(command + "\n")
e = self.tn.read_until("\r\n\r\nCM/Flash> ")
lines = e.split("\r\n")
if len(lines)==7:
response = lines[4].strip().replace(" ", "")
until = len(response) / 2
octecs_as_strings = [ response[2*i:2*i+2] for i in range(0,until)]
if len(octecs_as_strings) != BLOCK_SIZE:
# Continue to try again
continue
break
return octecs_as_strings
def process_block0(self, octecs_as_strings):
filename = "".join( \
[ c for c in \
map(lambda e: e.decode("hex"), octecs_as_strings[20:83]) \
if c != '\x00'])
payload_size_hex = "".join(octecs_as_strings[13:16])
payload_size = int(payload_size_hex,16)
total_size = int(payload_size_hex,16) + int("0x5c",16)
return filename, total_size
def write_block(self, file, octecs_as_strings):
as_decimals = map(lambda e: int(e,16), octecs_as_strings)
file.write(bytearray(as_decimals))
def open_image(self, image):
self.tn.write("open image%d\n" % image)
self.tn.read_until("\r\n\r\nCM/Flash> ")
def close_image(self):
self.tn.write("close\n")
#.........这里部分代码省略.........
示例10: __enter__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
class Remote:
def __enter__(self):
self.t = Telnet(HOST)
self.t.set_option_negotiation_callback(process_option)
self.t.set_debuglevel(DEBUG_LEVEL)
return self
def __exit__(self, type, value, traceback):
self.t.close()
return False
def is_on(self):
self.t.write("?P\r\n")
state = self.t.expect(["PWR1", "PWR0"], 0.2)
return state[2] == "PWR0"
def off(self):
self.t.write("PF\r\n")
# neet to set "network standby" to on in the receiver settings
# otherwise, this won't work
def on(self):
self.t.write("PO\r\n")
time.sleep(0.2)
self.t.write("PO\r\n")
# defining the actions to take
# between volume(-30) and volume(-40) is normally comfortable
def volume(self, negDezibel):
vol = negDezibel * 2 + 161
self.t.write("%03dVL\r\n" % vol)
def get_volume(self):
try:
self.t.write("?V\r\n")
match = self.t.expect(["VOL\d\d\d"], 0.2)
if match[0] == 0: # got valid volume
return (int(match[2].strip()[3:]) - 161) / 2
except:
pass
return -100
def get_device(self):
try:
self.t.write("?F\r\n")
match = self.t.expect(["FN\d\d"], 0.2)
if match[0] == 0: # valid device
return {
'FN02': "tuner",
"FN04": "PC",
"FN10": "TV",
"FN01": "AUX",
"FN25": "Pi"
}.get(match[2].strip(), "unknown")
except:
pass
return "n/a"
def select_tuner(self):
self.t.write("02FN\r\n")
def select_pc(self):
self.t.write("04FN\r\n")
def select_tv(self):
self.t.write("10FN\r\n")
def select_pi(self):
self.t.write("25FN\r\n")
def select_aux(self):
self.t.write("01FN\r\n")
def mute(self, should_mute):
if should_mute:
self.t.write("MO\r\n")
else:
self.t.write("MF\r\n")
示例11: MudClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import set_option_negotiation_callback [as 别名]
class MudClient(object):
"""A mud client.
There are three callbacks that may be set:
``on_connected()``
Called when a client has connected to the mud server.
``on_disconnected()``
Called when a client has disconnected from the mud server.
``on_line_received(text)``
Called when a text line is received from the mud server.
``on_gmcp_message_received(text)``
Called when a GMCP message is received from the mud server.
"""
def __init__(self, gmcp_support=True, mccp_support=True):
self._gmcp_support = gmcp_support
self._mccp_support = mccp_support
self.connecting = False
self.connected = False
self.on_connected = None
self.on_failed_to_connect = None
self.on_disconnected = None
self.on_line_received = None
self.on_gmcp_message_received = None
self._thread = None
self._connection = None
def connect(self, address, port):
"""Connect to a mud server at ``address``:``port``."""
if self.connected or self.connecting:
raise RuntimeError("Already connected or connecting.")
import gevent
self._thread = gevent.spawn(self._run, address, port)
self.connecting = True
def disconnect(self):
"""Disconnect from a mud server."""
self.connecting = False
if self._thread is not None:
self._thread.kill()
self._thread = None
def send(self, message):
"""Send a text message to the mud server."""
if self._connection:
self._connection.write(message)
def send_gmcp(self, message):
"""Send a GMCP message to the mud server."""
if self._connection:
s = IAC + SB + GMCP + message + IAC + SE
self._connection.get_socket().sendall(s)
def option_negotiation_callback(self, sock, cmd, opt):
if cmd == SE:
data = self._connection.read_sb_data()
if data[0] == GMCP:
self._callback(self.on_gmcp_message_received, data[1:])
if cmd == WILL:
if opt == GMCP and self._gmcp_support:
sock.sendall(IAC + DO + opt)
return
if opt == MCCP and self._mccp_support:
sock.sendall(IAC + DO + opt)
return
if cmd in (DO, DONT):
sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
sock.sendall(IAC + DONT + opt)
def _run(self, address, port):
try:
try:
self._connection = Telnet()
self._connection.set_option_negotiation_callback(
self.option_negotiation_callback)
self._connection.open(address, port, 5)
except IOError:
self._callback(self.on_failed_to_connect)
return
self.connecting = False
self.connected = True
self._callback(self.on_connected)
buf = ''
try:
while True:
try:
line = self._connection.read_until('\n', 2)
except EOFError:
break
if line:
self._callback(self.on_line_received, line)
finally:
self._callback(self.on_disconnected)
self._connection.close()
self._connection = None
finally:
self.connecting = False
#.........这里部分代码省略.........