本文整理汇总了Python中telnetlib.Telnet.open方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.open方法的具体用法?Python Telnet.open怎么用?Python Telnet.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类telnetlib.Telnet
的用法示例。
在下文中一共展示了Telnet.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: attempt
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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)
示例2: is_host_alive
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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
示例3: sendTo
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def sendTo(self, hosts=None, default_port=1000, module=0, msg=None):
"""
Send the message to the DEP.
If the argument 'hosts' is an IP or a list of IP's, it iterate over them to have an answer.
If the argument 'hosts' is an instance of DEPMessage, it uses the hosts known in the instance.
Open a connection to the DEP, sends the message and return the answer
in a synchronous manner.
"""
if msg:
self.message = msg
self.module = module
telnet = Telnet()
# t.set_debuglevel(100)
if isinstance(hosts, str):
hosts = (hosts,)
elif isinstance(hosts, DEPMessage):
self._hosts = hosts._hosts
hosts = self._hosts.keys()
for host in hosts or self.hosts:
try:
if host in self._hosts and self._hosts[host]:
telnet = self._hosts[host]
else:
logger.info('%s not active in %r', host, self._hosts)
if ':' in host:
telnet.open(*host.split(':'))
else:
telnet.open(host, default_port)
self._hosts[host] = telnet
sock = telnet.get_socket()
msg = self._build()
bytessent = sock.send(msg)
logger.debug('%d chars sent', bytessent)
answer, size = b'', None
while True:
answer += sock.recv(4096)
if not size and len(answer) >= 4:
size = int(codecs.encode(answer[:4][::-1], 'hex'), 16)
if len(answer) >= size:
break
readsel, _, _ = select([sock], [], [], 0.5)
if len(readsel) == 0:
answer += telnet.read_very_lazy()
break
break
except socket.error:
telnet.close()
self._hosts[host] = None
logger.exception('Socket issue with %s', host)
continue
else:
raise ValueError('No dep available in the list : ' +
str(hosts or self._hosts))
self.current_answer = codecs.encode(answer, 'hex').decode().upper()
if LOG_DEPCALLS: # pragma: no cover
with open('result.txt', 'ab') as out:
out.write(b'>>' + codecs.encode(msg[13:], 'hex').upper() + b':' + self.current_answer.encode().upper() + b'\n')
return self.current_answer
示例4: lineprofile
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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()
示例5: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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)
示例6: takeover_light
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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()
示例7: show
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def show(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 range(1,7):
if params[i+7] <> "":
tn.write(params[i+7] + "\n")
if "show board" in params[i+7]: tn.write(" ")
elif "slot" in params[i+7]:
print(tn.read_until("quit>", self.cmdTimeout)),
tn.write(" ")
elif "display" in params[i+7]:
print(tn.read_until(":", self.cmdTimeout)),
tn.write("\n ")
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()
示例8: open
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def open(self, *args, **kwargs):
"""
Works exactly like the Telnet.open() call from the telnetlib
module, except SSL/TLS may be transparently negotiated.
"""
Telnet.open(self, *args, **kwargs)
if self.force_ssl:
self._start_tls()
示例9: TelnetConnection
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
class TelnetConnection(object):
connection = None
message_count = 0
def __init__(self, host, port):
self.host = host
self.port = port
self.connection = Telnet()
self.connect()
def connect(self):
while True:
try:
self.connection.open(self.host, self.port,
timeout=TELNET_CONNECTION_TIMEOUT)
logging.info('Telnet connected to %s:%s' % (
self.host, self.port))
break
except socket.error as e:
logging.error('Telnet connect to %s:%s error: %s' % (
self.host, self.port, e))
gevent.sleep(TELNET_RECONNECT_TIMEOUT)
continue
handle = gevent.spawn(self.handle)
pool.add(handle)
def handle(self):
while True:
try:
line = self.connection.read_until('\r\n',
timeout=TELNET_READ_TIMEOUT)
line = line.strip()
logging.info('Got from %s:%s: %s (%s)' % (self.host, self.port, line, self.message_count))
self.message_count += 1
continue
except EOFError as e:
logging.error('Telnet read %s:%s error: %s' % (
self.host, self.port, e))
self.connect()
except Exception as e:
if e.message == 'timed out':
pass
def send(self, msg):
try:
self.connection.write('%s\r\n' % msg)
except socket.error as e:
logging.error('Cannot send to %s:%s: %s' % (
self.host, self.port, e))
self.connection.close()
self.connect()
示例10: connection_telnet
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def connection_telnet(hostname, port, sstring, timeout):
"""
Connects to a socket, checks for the WELCOME-MSG and closes the
connection.
Returns nothing.
"""
connection = Telnet()
connection.open(hostname, port)
connection.read_until(sstring, timeout)
connection.close()
示例11: _getCellAlarm
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [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
示例12: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def main(host, port):
telnet = Telnet()
telnet.open(host, port)
reader = ReaderThread(telnet)
reader.start()
while 1:
if not reader.isAlive(): break
line = raw_input()
telnet.write(line+'\n')
time.sleep(0.3)
telnet.close()
示例13: service_is_up
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def service_is_up(self, host):
# FIXME(nmg): this implemention is too ugly, maybe has a elegant way.
telnet = Telnet()
try:
telnet.open(str(host.host), int(host.port))
except socket.error:
return False
except error:
raise
finally:
telnet.close()
return True
示例14: __init__
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
class Client:
__slots__ = ("reader", "telnet", "uid")
def __init__(self, callback=None, uid=None):
self.uid = uid
host = "localhost"
port = 8080
self.telnet = Telnet()
self.telnet.open(host, port)
self.reader = ReaderThread(self.telnet, callback, uid)
self.reader.start()
def send_input(self, line):
self.telnet.write(line + "\n")
示例15: main
# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import open [as 别名]
def main(host, port):
telnet = Telnet()
telnet.open(host, port)
reader = ReaderThread(telnet)
reader.start()
while True:
if not reader.isAlive():
print 'giving up'
break
try:
line = raw_input()
except:
break
telnet.write(line + '\r\n')
print '\n'
os._exit(0)