本文整理汇总了Python中telnetlib.Telnet.expect方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.expect方法的具体用法?Python Telnet.expect怎么用?Python Telnet.expect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telnetlib.Telnet
的用法示例。
在下文中一共展示了Telnet.expect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: NASpowerdown
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def NASpowerdown(Nname,Nuser,Npass,Ncommand,Nport):
from telnetlib import Telnet
if Nname == "":
return _("no Name")
l=_("Connection Error")
try:
tn = Telnet(Nname, Nport, 5)
l=""
if Nuser != "":
l = l + tn.expect(['ogin:','sername'],10)[2]
l = l + tn.read_very_lazy()
tn.write('%s\r' % Nuser)
if Npass != "":
l = l + tn.read_until('assword:',10)
l = l + tn.read_very_lazy()
tn.write('%s\r' % Npass)
l = l + tn.expect(['#',">"],10)[2]
l = l + tn.read_very_lazy()
tn.write('%s\r' % Ncommand)
l = l + tn.expect(['#',">"],20)[2]
l = l + tn.read_very_lazy()
if config.plugins.elektro.NASwait.value == True:
tt = time() + 90
l = l + "\n waiting...\n"
while tt>time() and ping.doOne(Nname,1) != None:
sleep(2)
tn.write('exit\r')
l = l + tn.expect(['#',">"],5)[2]
l = l + tn.read_very_lazy()
tn.close()
finally:
return l
示例2: _connect
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def _connect(config):
"""Boilerplate to connect to a conviron."""
# Establish connection
telnet = Telnet(config.get("Conviron", "Host"))
response = telnet.expect([re.compile(b"login:")], timeout=TIMEOUT)
LOG.debug("Initial response is: {0!s}".format(response[2].decode()))
if response[0] < 0: # No match found
raise RuntimeError("Login prompt was not received")
# Username
payload = bytes(config.get("Conviron", "User") + "\n", encoding="UTF8")
telnet.write(payload)
response = telnet.expect([re.compile(b"Password:")], timeout=TIMEOUT)
LOG.debug("Sent username: {0!s}".format(payload.decode()))
LOG.debug("Received: {0!s}".format(response[2].decode()))
if response[0] < 0: # No match found
raise RuntimeError("Password prompt was not received")
# Password
payload = bytes(config.get("Conviron", "Password") + "\n", encoding="UTF8")
telnet.write(payload)
response = telnet.expect([re.compile(b"#")], timeout=TIMEOUT)
LOG.debug("Send password: {0!s}".format(payload.decode()))
LOG.debug("Received: {}".format(response[2].decode()))
if response[0] < 0: # No match found
raise RuntimeError("Shell prompt was not received")
return telnet
示例3: _connect_login
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def _connect_login(self):
telnet = Telnet(self.ip)
response = telnet.expect([re.compile(b'login'), ], timeout=TIMEOUT)
if response[0] < 0:
raise RuntimeError("Login prompt not recieved")
self.logger.debug("Intial response is: {0!s}".format(response[2].decode()))
# we MUST wait a little bit before writing to ensure that the stream isnt being written to.
time.sleep(0.1)
payload = bytes(self.telnet_username + "\n", encoding="UTF8")
telnet.write(payload)
response = telnet.expect([re.compile(b"Password:"), ], timeout=TIMEOUT)
self.logger.debug("Sent username: {0!s}".format(payload.decode()))
self.logger.debug("Received: {0!s}".format(response[2].decode()))
if response[0] < 0: # No match found
raise RuntimeError("Password prompt was not received")
# Password
payload = bytes(self.telnet_password + "\n", encoding="UTF8")
telnet.write(payload)
response = telnet.expect([shell_re, ], timeout=TIMEOUT)
self.logger.debug("Send password: {0!s}".format(payload.decode()))
self.logger.debug("Received: {}".format(response[2].decode()))
if response[0] < 0: # No match found
raise RuntimeError("Shell prompt was not received")
return telnet
示例4: Bras
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
class Bras(object):
""" Базовый класс для Брасов """
def __init__(self, di):
self.host = str(di["host"])
self.user = str(di["user"])
self.pwd = str(di["password"])
self.tn = None
self.clname = str(di["name"])
self.greet = str(di["greetings"])
def __login(self):
""" Метод для авторизации на Брасе
результат сохраняет в базовом классе """
self.tn = Telnet(self.host, 23, 5)
self.tn.get_socket().settimeout(TIMEOUT)
res = self.tn.expect(["Username:", "login:"], 5)
# telnet ok, but no greetings from server
if res[0] == -1:
self.tn.close()
return False
self.tn.write(self.user + "\n")
res = self.tn.expect(["Password:"], 5)
if res[0] == -1:
self.tn.close()
return False
self.tn.write(self.pwd + "\n")
# > ma5200 and e120, # asr, $ lisg
res = self.tn.expect([r">", r"#", r"\$"], 5)
if res[0] == -1:
self.tn.close()
return False
# we're in for sure
self.prepare_cli()
return True
def write(self, string):
""" Метод для ввода команды в телнет терминал """
try:
self.tn.read_very_eager()
self.tn.write(string + "\n")
except (EOFError, AttributeError, IOError):
res = self.__login()
if not res:
return False
self.tn.write(string + "\n")
except:
print_exc()
print_stack()
print("Exc in write bras")
res = self.__login()
if not res:
return False
self.tn.write(string + "\n")
return True
示例5: _run_command
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def _run_command(self, cmd: str, ok="OK") -> bool:
"""
sends a telnet command to the host
:param cmd:
:return: bool successful
"""
telnet = Telnet(self.ip, self.telnet_port, 60)
try:
response = telnet.read_until(b'>', timeout=0.1)
self.logger.debug("Intial response is: {0!s}".format(response.decode()))
# we MUST wait a little bit before writing to ensure that the stream isnt being written to.
time.sleep(0.5)
# encode to ascii and add LF. unfortunately this is not to the telnet spec (it specifies CR LF or LF CR I'm ns)
telnet.write(cmd.encode("ascii") + b"\n")
ok_regex = re.compile(b'.*'+ok.encode("ascii")+b'.*')
response = telnet.expect([ok_regex], timeout=30)
if response[0] < 0:
return False
else:
return True
except:
self.logger.error(traceback.format_exc())
return False
finally:
telnet.close()
示例6: _show_run
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def _show_run(self,get_switch,get_switch_property,get_switch_access):
### variable arrange
switch_name = get_switch['name']
network_inform = get_switch['ip']
telnet_port = network_inform.split(':')[1]
telnet_ip = network_inform.split(':')[0].split('/')[0]
telnet_user = get_switch_access['account']
telnet_pass = get_switch_access['password']
telnet_enable = get_switch_access['enable']
### telnet open time out in second
self.telnet_open_timeout = float(10)
### telnet open processing
try:
telnet_pointer = Telnet(telnet_ip,telnet_port,self.telnet_open_timeout)
except:
msg="[ error : "+time.asctime()+" ] can't open the telnet, ip : "+telnet_ip+", port :"+telnet_port
self.logging_msg(self.run_syslog,msg)
sys.exit()
### telnet login processing
try:
line_result = telnet_pointer.expect(Arista_manage._login_pattern,self.telnet_open_timeout)[1]
except:
msg="[ error : "+time.asctime()+" ] can't 2read login pattern : "+str(Arista_manage._login_pattern)
self.logging_msg(self.run_syslog,msg)
sys.exit()
if not line_result:
sys.exit()
### insert account for login
telnet_pointer.write(telnet_user+"\n")
### wait the password pattern
try:
telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout)
except:
msg="[ error : "+time.asctime()+" ] can't read login pattern : "+str(Arista_manage._passwd_pattern)
self.logging_msg(self.run_syslog,msg)
sys.exit()
telnet_pointer.write(telnet_pass+"\n")
print telnet_pointer.expect([switch_name+"\w*>"],self.telnet_open_timeout)
telnet_pointer.write("enable1234\n")
print telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout)
telnet_pointer.write(telnet_enable+"\n")
print telnet_pointer.expect([switch_name+"\w*#"],self.telnet_open_timeout)
telnet_pointer.write("exit\n")
telnet_pointer.read_all()
telnet_pointer.close()
示例7: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [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")
示例8: tlnt_connect
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [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
示例9: get_cluster_info
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def get_cluster_info(host, port, ignore_cluster_errors=False):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'version\n')
res = client.read_until(b'\r\n').strip()
version_list = res.split(b' ')
if len(version_list) not in [2, 3] or version_list[0] != b'VERSION':
raise WrongProtocolData('version', res)
version = version_list[1]
if StrictVersion(smart_text(version)) >= StrictVersion('1.4.14'):
cmd = b'config get cluster\n'
else:
cmd = b'get AmazonElastiCache:cluster\n'
client.write(cmd)
regex_index, match_object, res = client.expect([
re.compile(b'\n\r\nEND\r\n'),
re.compile(b'ERROR\r\n')
])
client.close()
if res == b'ERROR\r\n' and ignore_cluster_errors:
return {
'version': version,
'nodes': [
'{0}:{1}'.format(smart_text(host),
smart_text(port))
]
}
ls = list(filter(None, re.compile(br'\r?\n').split(res)))
if len(ls) != 4:
raise WrongProtocolData(cmd, res)
try:
version = int(ls[1])
except ValueError:
raise WrongProtocolData(cmd, res)
nodes = []
try:
for node in ls[2].split(b' '):
host, ip, port = node.split(b'|')
nodes.append('{0}:{1}'.format(smart_text(ip or host),
smart_text(port)))
except ValueError:
raise WrongProtocolData(cmd, res)
return {
'version': version,
'nodes': nodes
}
示例10: QYT_TelnetClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def QYT_TelnetClient(ip, username, password, enable, *cmds):
tn = Telnet(ip, 23)
rackreply = tn.expect([],timeout=1)[2].decode().strip()#读取回显
print(rackreply)#打印回显
tn.write(username.encode())#任何字串都需要转成二进制字串
tn.write(b'\n')#注意一定要打回车
time.sleep(1)#在命令之间留出一定的时间间隔!否则路由器可能反应不过来
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
tn.write(password.encode())
tn.write(b'\n')
time.sleep(1)
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
tn.write(b'enable\n')
time.sleep(1)
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
tn.write(enable.encode())
tn.write(b'\n')
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
time.sleep(1)
for cmd in cmds:#读取命令,并且逐个执行!
tn.write(cmd.encode() + b'\n')
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
time.sleep(1)
tn.write(b'exit\n')
rackreply = tn.expect([],timeout=1)[2].decode().strip()
print(rackreply)
tn.close()
示例11: login
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def login(self):
user = '{0}\n'.format(self.user)
pwd = '{0}\n'.format(self.password)
tn = Telnet(self.ip, 23, 5)
res = tn.expect(['Username:'], 5)
if res[0] == -1:
tn.close()
return False
tn.write(user)
tn.read_until('Password:', 5)
tn.write(pwd)
res = tn.expect(['>'], 5)
if res[0] == -1:
tn.close()
return False
tn.write('system-view\n')
tn.read_until(']')
return tn
示例12: QYT_TelnetClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [as 别名]
def QYT_TelnetClient(ip, username, password, cmd):
tn = Telnet(ip, 23)
rackreply = tn.expect([],timeout=1)[2].decode().strip()#读取回显
#print(rackreply)#打印回显
tn.write(username.encode())#任何字串都需要转成二进制字串
tn.write(b'\n')#注意一定要打回车
time.sleep(1)#在命令之间留出一定的时间间隔!否则路由器可能反应不过来
rackreply = tn.expect([],timeout=1)[2].decode().strip()
#print(rackreply)
tn.write(password.encode())
tn.write(b'\n')
time.sleep(1)
rackreply = tn.expect([],timeout=1)[2].decode().strip()
#print(rackreply)
tn.write('terminal length 0'.encode() + b'\n')
time.sleep(1)
rackreply = tn.expect([],timeout=1)[2].decode().strip()
#print(rackreply)
tn.write(cmd.encode() + b'\n')
time.sleep(1)
rackreply = tn.expect([],timeout=1)[2].decode().strip()
#print(rackreply)
result = rackreply
time.sleep(1)
tn.write(b'exit\n')
rackreply = tn.expect([],timeout=1)[2].decode().strip()
#print(rackreply)
tn.close()
return result
示例13: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [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'))
示例14: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [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
示例15: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import expect [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