import argparse import socket import telnetlib import time from decimal import Decimal class TelnetSun(telnetlib.Telnet): message_list = [] rule = [b'Login', b'Password', b'Username'] def msg(self, msg, *args): """ 重写 """ if 'recv' in msg: TelnetSun().message_list.append(args[0]) if self.debuglevel > 0: print('Telnet(%s,%s):' % (self.host, self.port), end=' ') if args: print(msg % args) else: print(msg) def read_until_new(self, timeout=None): from time import monotonic as _time import selectors if hasattr(selectors, 'PollSelector'): _TelnetSelector = selectors.PollSelector else: _TelnetSelector = selectors.SelectSelector rule = TelnetSun.rule for match in rule: n = len(match) self.process_rawq() i = self.cookedq.find(match) if i >= 0: i = i + n buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf if timeout is not None: deadline = _time() + timeout with _TelnetSelector() as selector: selector.register(self, selectors.EVENT_READ) while not self.eof: if selector.select(timeout): i = max(0, len(self.cookedq) - n) self.fill_rawq() self.process_rawq() i = self.cookedq.find(match, i) if i >= 0: i = i + n buf = self.cookedq[:i] self.cookedq = self.cookedq[i:] return buf if timeout is not None: timeout = deadline - _time() if timeout < 0: break return self.read_very_lazy() class TelnetDetect: def __init__(self, host, port): self.host = host self.port = port self.rule = [b'Login', b'Password', b'Username'] def get_ret(self, obj, ret_list=None): if ret_list is None: ret_list = [] try: ret = obj.recv(1024) obj.settimeout(50) except: print('呵呵呵', ret_list) return self.get_ret(obj, ret_list=ret_list) for r in self.rule: if r in ret or r.lower() in ret: try: ret = str(ret, encoding="utf-8") except: pass ret_list.append(ret) return ret_list elif b'' == ret or '' == ret: return self.get_ret(obj, ret_list=ret_list) else: try: ret = str(ret, encoding="utf-8") ret_list.append(ret) except: pass return self.get_ret(obj, ret_list=ret_list) def connect_old(self): obj = socket.socket() obj.connect((self.host, self.port)) # 连接目标 rule = [b'BCM96328', b'Router'] ret = self.get_ret(obj) return ret def connect(self): try: tn = TelnetSun(self.host, self.port, timeout=60) tn.set_debuglevel(1) tn.read_until_new(timeout=60) message_list = tn.message_list ret_list = [] for ret in message_list: try: ret = str(ret, encoding="utf-8") ret_list.append(ret) except: pass return ret_list except Exception as e: return e.args[0] def opt(): parser = argparse.ArgumentParser(description='命令行中传入命令') parser.add_argument('-host', required=True, help='<host(主机)>') parser.add_argument('-port', type=int, help='<port(端口)>', default=23) parser.add_argument('-timeout', type=int, help='<间隔时间>', default=0) return parser.parse_args() def get_host(host): host_list = [] if '-' in host: h = host.split('-') left_host = h[0] left_host_list = left_host.split('.') right_host = h[1] right_host_list = right_host.split('.') for i in range(int(left_host_list[-1]), int(right_host_list[-1]) + 1): d = left_host_list[:3] + [str(i)] host_list.append('.'.join(d)) elif '*' in host: rule = { '0': {'m': 1, 'n': 255 + 1}, '1': {'m': 0, 'n': 99 + 1}, '2': {'m': 0, 'n': 9 + 1}, } h = host.split('.') r = h[-1].split('*')[0] for i in range(rule['{}'.format(len(r))]['m'], rule['{}'.format(len(r))]['n']): d = h[:3] + ['{}{}'.format(r, i)] host_list.append('.'.join(d)) else: host_list.append(host) return host_list def main(flag=False, **kwargs): start_time = Decimal(time.time()).quantize(Decimal("0.00")) if flag: host = kwargs.get('host') port = kwargs.get('port') timeout = kwargs.get('timeout') if not timeout: timeout = 0 host_list = get_host(host) else: args = opt() host_list = get_host(args.host) port = args.port timeout = args.timeout text = [] for host in host_list: ret = TelnetDetect(host, port).connect() d = { 'host': host, 'port': port, 'ret': ret, } text.append(d) time.sleep(timeout) end_time = Decimal(time.time()).quantize(Decimal("0.00")) print('结果为:\n{},\n用时:{}s'.format(text, end_time - start_time)) return {'result': text, 'hold_time': '{}s'.format(end_time - start_time)} if __name__ == '__main__': main() # host = '192.168.79.136' # host = '71.114.130.46' # host = '186.151.203.89' # port = 23 # r = TelnetDetect(host, port).connect() # for i in r: # print(i)