当前位置: 首页>>代码示例>>Python>>正文


Python Telnet.get_socket方法代码示例

本文整理汇总了Python中telnetlib.Telnet.get_socket方法的典型用法代码示例。如果您正苦于以下问题:Python Telnet.get_socket方法的具体用法?Python Telnet.get_socket怎么用?Python Telnet.get_socket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telnetlib.Telnet的用法示例。


在下文中一共展示了Telnet.get_socket方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Bras

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [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
开发者ID:hh-h,项目名称:ossdev,代码行数:57,代码来源:Bras.py

示例2: sendTo

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [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
开发者ID:NormanDenayer,项目名称:dep,代码行数:62,代码来源:dep.py

示例3: ClientNetworkCore

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [as 别名]
class ClientNetworkCore(SingletonCore,QObject):
    instance = None
    
    THREADED_REQUESTS = False
    
    waiting_response = Event()
    threaded_response = None
    
    def __init__(self):
        QObject.__init__(self)
        
        self.HOST = 'localhost'
        self.PORT = 50007
        
        self.status = 'DESCONECTADO'
        self.connected = False
        self.last_success_request = (datetime.now() - timedelta(hours=1))
    
    def dump_configuration(self):
        return {'HOST': self.HOST,
                'PORT': self.PORT}
    def load_configuration(self,conf):
        if 'HOST' in conf:
            self.HOST = conf['HOST']                        
        if 'PORT' in conf:
            self.PORT = conf['PORT']
    
#     def timerEvent(self,event):
#         print "sucedio el evento en el client network core"
        
#     def start_timer(self):
#         self.clock_id = self.startTimer(1000)
        
#     def stop_timer(self):
#         self.killTimer(self.clock_id)
    
    def connect(self):
        try :
            self.conection = Telnet(self.HOST,self.PORT)
            self.sock = self.conection.get_socket()
            self.fd = self.sock.makefile()
            
            self.status = 'CONECTADO'
            self.connected = True
        except Exception, e:
            new_e = NetworkException( "No se pudo establecer la \
conexion con el server.\n Cheque que la direccion sea correcta o el server este encendido")
            new_e.log_level_msg = e.message
            raise new_e
开发者ID:juanchitot,项目名称:domo,代码行数:51,代码来源:client_network_core.py

示例4: Telnet

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [as 别名]
sys.path.append('/home/bluec0re/sources/pentesting_utils/ctf')
from telnetlib import Telnet
from pprint import pprint
from timing import timeit
import string

TARGET = ('192.168.56.101', 54311)

#s = socket.create_connection(TARGET)

tn = Telnet(*TARGET)
print(tn.read_until(b'in\n').decode())

#print(tn.read_until(b':').decode())

s = tn.get_socket()


def callback(pwd):
    s.send(pwd)
    data = s.recv(512)
    if b'succ' in data:
        raise Exception(pwd)

pwd = ''
s = tn.get_socket()
while True:
    timings = []
    for i, c in enumerate(string.ascii_letters + string.digits):
        sys.stderr.write("\r{}".format(c))
        pwd2 = pwd + c
开发者ID:bluec0re,项目名称:CTFs,代码行数:33,代码来源:secure_remote_shell2.py

示例5: Telnet

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [as 别名]
        print "se produjo una excepcion en la lectura"
    
    compresed = r_data.rstrip("\n")
    compresed = compresed.decode("hex")
    yaml_coded = zlib.decompress(compresed)
    print yaml_coded

HOST = '192.168.1.12' # The remote host
PORT = 50007              # The same port as used by the server
try :
    conection = Telnet(HOST,PORT)
except Exception, e:
    print "No se pudo establecer la conexion %s " % e
    sys.exit()
conected = True
sock = conection.get_socket()
fd = sock.makefile()

while conected:
    if fd.closed :
        break
    comando = raw_input("ingrese el comando: ")
    if comando == 'ok' :
        l = LightMap()
        l.name="luces cocina"
        l.comment="comentraio sobre las luces de la cocina"        
        n = NetMsg()
        n.method='map_light'
        n.params=[l]
        n.status="conectado"
        encoded = zlib.compress(yaml.dump(n)).encode('hex')
开发者ID:juanchitot,项目名称:domo,代码行数:33,代码来源:test_network_client.py

示例6: __init__

# 需要导入模块: from telnetlib import Telnet [as 别名]
# 或者: from telnetlib.Telnet import get_socket [as 别名]
class rokuSB:
    def __init__(self, dtype):
        self.sb = Telnet()
        self.dpytype = dtype
        self.host = None

    def open(self, host):
        try:
            self.sb.open(host, 4444, 10)
            prompt = self.sb.expect([b'SoundBridge> ', b'sketch> '], 2)
            if (prompt[0] == -1):
                print("SB not responding")
                self.sb.close()
                return False

        except (ConnectionError, socket.error) as err:
            print("SoundBridge '{}', not found or connect failure = {}".format(host, err))
            return False

        # Save host for reopen()
        self.host = host
        # Set character encoding default
        self.msg(encoding='utf8')
        self.cmd("irman echo")
        return True

    def reopen(self):
        if (self.host is None):
            return False
        assert(self.sb.get_socket() is None)
        return self.open(self.host)

    def close(self):
        if (self.sb.get_socket() is None):
            return
        try:
            # self.cmd("sketch -c clear")
            self.cmd("sketch -c exit")
            self.cmd("irman off")
            self.cmd("exit")
        except socket.error:
            print("Socket error in close = {}", sys.exc_info())
        finally:
            if (self.sb.get_socket() is not None):
                self.sb.close()

    # Optional args to msg (soundbridge display)
    #
    # text          - default none - can be omitted to just set font and encoding
    # x,y  location - default 0,0
    # font          -
    # clear         - 0/1 force the display to clear first (default 0)
    # encoding      - set roku text encoding
    #
    def msg(self, **kwargs):
        x = kwargs.get('x', 0)
        y = kwargs.get('y', 0)
        text = kwargs.get('text')
        clear = kwargs.get('clear', False)
        font = kwargs.get('font')
        encoding = kwargs.get('encoding')

        if (encoding is not None):
            self.cmd("sketch -c encoding " + str(encoding))

        if (font is not None):
            self.cmd("sketch -c font " + str(font))

        if (text is None):
            return

        if (clear):
            self.clear()

        self.cmd('sketch -c text {} {} "{}"'.format(x, y, text))
        return

    def cmd(self, text):
        try:
            self.sb.write(text.encode('utf-8') + b'\n')
        except socket.error:
            print("Socket error in write = {}", sys.exc_info())
            if (self.sb.get_socket() is not None):
                self.sb.close()
            raise

    def clear(self):
        self.cmd("sketch -c clear")

    # Handle input and look for IR commands between panels
    def keyproc(self, timeout):
        self.cmd("irman intercept")
        try:
            msg = self.sb.expect([b'irman: (.*)$'], timeout)
        except EOFError:
            if (self.sb.get_socket() is not None):
                self.sb.close()
            raise

        # Got an IR code - pass it on to SB and exit app
#.........这里部分代码省略.........
开发者ID:thess,项目名称:rokuweather,代码行数:103,代码来源:roku_tn.py


注:本文中的telnetlib.Telnet.get_socket方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。