本文整理汇总了Python中telnetlib.Telnet.close方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.close方法的具体用法?Python Telnet.close怎么用?Python Telnet.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telnetlib.Telnet
的用法示例。
在下文中一共展示了Telnet.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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])
示例2: send_config
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
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
示例3: Player
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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()
示例4: NASpowerdown
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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
示例5: QYT_TelnetClient
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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
示例6: lineprofile
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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()
示例7: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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)
示例8: run
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
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"
示例9: upnpbind
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
def upnpbind(ex_port=None):
location = search_device()
in_ip = get_internal_ip_address(location)
control_url = get_control_url(location)
ex_ip = get_external_ip_address(control_url)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((in_ip, 0))
s.listen(1)
in_addr = s.getsockname()
if ex_port:
ex_addr = (ex_ip, ex_port)
else:
ex_addr = (ex_ip, in_addr[1])
print >>sys.stderr, "[+] bind: %r" % (in_addr,)
add_port_mapping(control_url, ex_addr, in_addr)
try:
c, remote_addr = s.accept()
print >>sys.stderr, "[+] accept: %r" % (remote_addr,)
s.close()
t = Telnet()
t.sock = c
t.interact()
t.close()
finally:
delete_port_mapping(control_url, ex_addr)
示例10: update
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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)
示例11: connect
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
def connect(self):
tn = Telnet("localhost")
out = tn.read_until("login:", 3)
tn.write("root\n")
check = tn.read_until("Password:", 2)
out += check
if check.__contains__("Password:"):
tn.write(self.oldp + "\n")
check = tn.read_until("~#", 2)
out += check
if check.__contains__("~#"):
tn.write("passwd\n")
out += tn.read_until("password", 2)
tn.write(self.newp + "\n")
out += tn.read_until("password", 2)
tn.write(self.newp + "\n")
out += tn.read_until("xxx", 1)
tn.write("exit\n")
out += tn.read_all()
else:
out += "\nLogin incorrect, wrong password."
tn.close()
self.connected = False
self["lab"].setText(out)
示例12: is_host_alive
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
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
示例13: takeover_light
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
def takeover_light(ip):
t = Telnet()
t.open(ip, 30000)
t.write("[Link,Touchlink]")
output = t.read_until("[Link,Touchlink,success", 10)
print output
t.close()
示例14: TelnetConnect
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [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()
示例15: attempt
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import close [as 别名]
def attempt(host, port, timeout, outputFile, secondCall = False):
try:
tn = Telnet(host,port,timeout)
tn.open(host,port,timeout)
header = tn.read_some()
tn.close()
print "[!] Port %d seems to be open on %s" %(port,host)
file = open(outputFile, 'a') #writes to file
file.write("%s:%d"%(host,port))
if header != "":
file.write(" - %s"%(header))
file.write("\n")
file.close()
except Exception, e:
try:
e[1]
code, reason = e.args
print "[ERROR] %s on %s:%d (%d)" %(reason,host,port,code)
except IndexError:
if e.args[0] == "timed out" and port in commonOpenPorts:
if secondCall is False:
print "[!] extending timeout on common port (%d)" %(port)
return attempt(host, port, (timeout*2), outputFile, True)
#only write timeouts to the file
if e.args[0] == "timed out":
file = open(outputTimeoutFile, 'a') #writes to file
file.write("%s:%d"%(host,port))
file.write("\n")
file.close()
print "[ERROR] %s on %s:%d " %(e.args[0],host,port)