Ejemplo n.º 1
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while 1:
        if not reader.isAlive():
            print 'giving up'
            break
        try:
            line = raw_input()
        except:
            break
        telnet.write(line + '\r\n')
    print '\n'
    os._exit(0)
Ejemplo n.º 2
0
def simu_login():
    log = module_logger.log
    log.debug("Starting Simu login procedure")
    # TODO: Consider handling game_connection with a context manager, if possible
    creds = get_credentials()
    key = eaccess_protocol(creds)
    game_connection = Telnet(DR_HOST, DR_PORT)
    log.debug("Got a game connection via Telnet")
    game_connection.read_until(b"</settings>")
    game_connection.write(key.encode("ASCII") + b"\n")
    game_connection.write(b"/FE:STORMFRONT /VERSION:1.0.1.26 /P:" +
                          platform.system().encode("ASCII") + b" /XML\n")
    sleep(0.3)
    game_connection.write(b"<c>\n")
    sleep(0.3)
    game_connection.write(b"<c>\n")
    log.debug("simu_login finished")
    return game_connection
Ejemplo n.º 3
0
 def __init__(self, host, port):
     self.telnet = Telnet(host, port)
     self.method_list = inspect.getmembers(self, predicate=inspect.ismethod)
     self.action_mapping = {
         'register': self.Register,
         'login': self.Login,
         'logout': self.Logout,
         'create-post': self.CreatePost,
         'comment': self.Comment,
         'read': self.Read,
         'delete-post': self.DeletePost,
         'update-post': self.UpdatePost,
         'mail-to': self.MailTo,
         'retr-mail': self.RetrMail,
         'delete-mail': self.DeleteMail
     }
     self.s3_conn = boto3.resource('s3')
     self.bucket = None
Ejemplo n.º 4
0
 def __init__(self, host, port):
     self._tc = Telnet(host, port)
     self._socket = (host, port)
     sleep(WAIT_AFTER_CONNECT)
     self._receive()
     # for some reason first send-receive does not work, so dummy
     tmp = self._last_read
     self._show('ADEV')
     if tmp.find('Welcome') == -1:
         self.tc.close()
         self._connected = False
         self._last_read = None
         self._socket = None
         self._tc = None
     else:
         self._show(TSC5120A.show_params.keys()[0])
         self._connected = True
         self._last_read = tmp
Ejemplo n.º 5
0
def check(hostname):
    """
    Check to see if a device supports telnet

    @param hostname: name or IP address of device
    @type hostname: string
    @return: whether or not telnet port is available
    @rtype: integer
    @todo: support alternate ports
    """
    from telnetlib import Telnet
    import socket
    try:
        tn = Telnet(hostname)
        tn.close()
        return 1
    except socket.error:
        return 0
Ejemplo n.º 6
0
 def update(self):
     """Get the latest data from HDDTemp running as daemon."""
     try:
         connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT)
         data = (
             connection.read_all()
             .decode("ascii")
             .lstrip("|")
             .rstrip("|")
             .split("||")
         )
         self.data = {data[i].split("|")[0]: data[i] for i in range(0, len(data), 1)}
     except ConnectionRefusedError:
         _LOGGER.error("HDDTemp is not available at %s:%s", self.host, self.port)
         self.data = None
     except socket.gaierror:
         _LOGGER.error("HDDTemp host not found %s:%s", self.host, self.port)
         self.data = None
Ejemplo n.º 7
0
def LogParsing(hostnames,NE_IP) :

  #####텔넷 접속#####
  telnet =Telnet(NE_IP)
  telnet.read_until('<') #"<" 이 나올때까지 문자열 읽어들임, 저장은 안함
  telnet.write('ACT-USER:'******':ADMIN:CTAG::ADMIN:;') # TL1 로그인 명령
  telnet.read_until('<')

  #####경보조회 명령실행#####
  telnet.write('RTRV-ALM-ALL:'+hostnames+':ALL:CTAG:::,;') #TL1 경보조회 명령
  Logs=telnet.read_until('<') #< 이 나올때까지 RTRV로그를 읽어서 Log에 저장
  print hostnames + '(' + NE_IP + ')' + ' Parsing Completed!'

  #####텔넷 종료####
  telnet.write('CANC-USER:'******':ADMIN:CTAG;') #TL1 로그오프 명령
  telnet.close()

  return Logs # Log반환
Ejemplo n.º 8
0
def bofh(host="bofh.jeffballard.us", port=666, timeout=180, secondcall=False):
    try:
        tn = Telnet(host, port, timeout)
        tn.open(host, port, timeout)
        header = tn.read_all()
        new_header = header[161:]
        print(new_header)
        tn.close()
        print("[!] Port %d seems to be open on %s" % (port, host))

    except Exception as e:
        try:
            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 port:
                if secondcall is False:
                    print("[!] extending timeout on common port (%d)" % port)
Ejemplo n.º 9
0
def TelnetClient(ip, username, password, cmd_list, enable='csr', verbose=True):
    tn = Telnet(ip, 23)
    # print(tn.expect([], timeout=1))
    # print(tn.expect([], timeout=1)[2])
    # print(tn.expect([], timeout=1)[2].decode())
    # print(tn.expect([], timeout=1)[2].decode().strip())
    rackreply = tn.expect([], timeout=1)[2].decode().strip()  # 读取回显
    if verbose:
        print(rackreply)  # 打印回显
    tn.write(username.encode())  # 任何字串都需要转成二进制字串
    tn.write(b'\n')  # 注意一定要打回车
    time.sleep(1)  # 在命令之间留出一定的时间间隔!否则路由器可能反应不过来
    rackreply = tn.expect([], timeout=1)[2].decode().strip()
    if verbose:
        print(rackreply)  # 打印回显
    tn.write(password.encode())
    tn.write(b'\n')
    time.sleep(1)
    rackreply = tn.expect([], timeout=1)[2].decode().strip()
    if verbose:
        print(rackreply)  # 打印回显
    if enable is not None:
        tn.write(b'enable\n')
        time.sleep(1)
        rackreply = tn.expect([], timeout=1)[2].decode().strip()
        if verbose:
            print(rackreply)  # 打印回显
        tn.write(enable.encode())
        tn.write(b'\n')
        rackreply = tn.expect([], timeout=1)[2].decode().strip()
        if verbose:
            print(rackreply)  # 打印回显
    time.sleep(1)
    for cmd in cmd_list:  # 读取命令,并且逐个执行!
        tn.write(cmd.encode() + b'\n')
        rackreply = tn.expect([], timeout=1)[2].decode().strip()
        if verbose:
            print(rackreply)  # 打印回显
        time.sleep(1)
    tn.write(b'exit\n')
    rackreply = tn.expect([], timeout=1)[2].decode().strip()
    if verbose:
        print(rackreply)  # 打印回显
    tn.close()
Ejemplo n.º 10
0
 def detect(self, port):
     atvendortable = {
         0x1199: ["Sierra Wireless", 3],
         0x2c7c: ["Quectel", 3],
         0x19d2: ["ZTE", 2],
         0x413c: ["Telit", 3],
         0x0846: ["Netgear", 2],
         0x04E8: ["Samsung", -1]
     }
     mode = "Unknown"
     for device in self.detectusbdevices():
         if device.vid == vendor.zte.value:
             if device.pid == 0x0016:
                 print(
                     f"Detected a {atvendortable[device.vid][0]} device with pid {hex(device.pid)} in AT mode"
                 )
                 mode = "AT"
                 break
             elif device.pid == 0x1403:
                 print(
                     f"Detected a {atvendortable[device.vid][0]} device with pid {hex(device.pid)} in Web mode"
                 )
                 mode = "Web"
                 url = 'http://192.168.0.1/goform/goform_set_cmd_process?goformId=USB_MODE_SWITCH&usb_mode=6'
                 if self.websend(url):
                     print("Successfully enabled adb.")
                 break
         elif device.vid == vendor.netgear.value:
             try:
                 # vid 0846, netgear mr1100, mr5100
                 self.tn = Telnet("192.168.1.1", 5510, 5)
                 self.connected = True
             except:
                 self.connected = False
     if mode == "AT" or mode == "Unknown":
         for port in self.getserialports():
             if port.vid in atvendortable:
                 portid = port.location[-1:]
                 if int(portid) == atvendortable[port.vid][1]:
                     print(
                         f"Detected a {atvendortable[port.vid][0]} at interface at: "
                         + port.device)
                     return port.device
     return ""
Ejemplo n.º 11
0
def verify_update(args):
    success = False
    firmware_tag = ''

    def find_tag(tag):
        if tag in firmware_tag:
            print("Verification passed")
            return True
        else:
            print("Error: verification failed, the git tag doesn't match")
            return False

    try:
        # Specify a longer time out value here because the board has just been
        # reset and the wireless connection might not be fully established yet
        tn = Telnet(args.ip, timeout=15)
        print("Connected via telnet again, lets check the git tag")

        firmware_tag = tn.read_until(b'with CC3200')
        tag_file_path = args.file.rstrip('mcuimg.bin') + 'genhdr/mpversion.h'

        if args.tag is not None:
            success = find_tag(bytes(args.tag, 'ascii'))
        else:
            with open(tag_file_path) as tag_file:
                for line in tag_file:
                    bline = bytes(line, 'ascii')
                    if b'MICROPY_GIT_HASH' in bline:
                        bline = bline.lstrip(
                            b'#define MICROPY_GIT_HASH ').replace(
                                b'"', b'').replace(b'\r',
                                                   b'').replace(b'\n', b'')
                        success = find_tag(bline)
                        break

    except Exception as e:
        print_exception(e)
    finally:
        try:
            tn.close()
        except Exception as e:
            pass
        return success
Ejemplo n.º 12
0
 def initiate(self, ip="192.168.1.24", port=8325):
     try:
         self.connect = Telnet(ip, port, timeout=37)
         if self.connect.sock:
             self.connect.sock.send(IAC + NOP)
     except:
         print("The door is NOT yet open!")
     # self.connect.write("remote\n".encode('ascii'))
     # print(self.connect.read_until(b"\r\n").decode('ascii').replace('\r\n',''))
     self.connect.write("control 1\n".encode('ascii'))
     control = self.connect.read_until(b"\r\n").decode('ascii').replace(
         '\r\n', '')
     self.connect.write("remote 1\n".encode('ascii'))
     remote = self.connect.read_until(b"\r\n").decode('ascii').replace(
         '\r\n', '')
     if remote.split(': ')[1] == '1':
         print("Dilution connected: %s" % control.split(' ')[3])
     else:
         print("NO remote: make sure the server is configured correctly!")
Ejemplo n.º 13
0
    def findDataFromDevice(self, device, label):
        deviceArray = list()
        # print(f'finding data from [{device}] with label [{label}]')
        sensors = psutil.sensors_temperatures()
        for i, sensor in enumerate(sensors):
            # print(f'index {i} sensor {sensor}')
            if (sensor == device) and (sensors[sensor][i].label == label):
                deviceArray.append({
                    'device': device,
                    'label': label,
                    'temperature': sensors[sensor][i].current
                })

        # maybe hddtemp
        if self.hddtempIsOk():
            with Telnet('127.0.0.1', 7634) as tn:
                lines = tn.read_all().decode('utf-8')

            if lines != '':
                data = lines
                # remove first char
                data = data[1:]
                # remove the last char
                data = ''.join(
                    [data[i] for i in range(len(data)) if i != len(data) - 1])
                # replace double || by one |
                data = data.replace('||', '|')
                # convert to array
                data = data.split('|')
                dataLen = len(data)
                forLenght = int(dataLen / 4)

                newarray = self.chunkIt(data, forLenght)
                for na in newarray:
                    if (device == na[0]) and (label == na[1]):
                        deviceArray.append({
                            'device': na[0],
                            'label': na[1],
                            'temperature': na[2]
                        })

        # print(deviceArray)
        return deviceArray
Ejemplo n.º 14
0
 def connect(self):
     try:
         self.tn = Telnet(self.host)
         if self.tn.read_until("Username:"******"Username:"******"%s\r", % self.username)
         if self.tn.read_until("Password:"******"Password:"******"%s\r" % self.password):
         elif self.tn.read_until("Username:"******"Wrong password")
             return "Invalid Password"
         if self.tn.read_until(self.prompt):
             self.log.append("Connected to %s" % self.host)
             return self.tn
         else:
             return "Something wrong...."
     except:
         return "Cannot connect to %s with %s %s" % (self.host, self.username, self.password)
Ejemplo n.º 15
0
def get_telnet_status (host, port=23, timeout=2):
    """ Determines whether Telnet is open on the specified remote host.
    Args:
        host (str): The address of the remote host
        port (int): The port to scan
        timeout (float): The number of seconds to wait before timeout
    Returns:
        True if Telnet is open and listening on the remote host, otherwise false
    """
    result = TelnetStatus.UNKNOWN
    try:
        with Telnet(host, port, timeout=timeout) as tn:
            tn.read_some() # Read a little bit from the socket.
            result = TelnetStatus.TELNET_OPEN
    except ConnectionRefusedError:
        result = TelnetStatus.CONN_REFUSED
    except OSError:
        result = TelnetStatus.HOST_UNREACHABLE
    return result
Ejemplo n.º 16
0
async def process_evennia(ctx):
    if ctx.author.id not in telnet_connections:
        tn = Telnet('localhost', 4000)
        telnet_connections[ctx.author.id] = tn
        time.sleep(delay)
        output = get_tn_output(tn)
        time.sleep(delay)
        #await ctx.channel.send(output)
        output = interact_tn(tn, f'create {ctx.author.id} c67jHL8p\n')
        #await ctx.channel.send(output)
        output = interact_tn(tn, f'connect {ctx.author.id} c67jHL8p\n')
        await send_long_message(ctx.channel, message=output)

    tn = telnet_connections[ctx.author.id]
    output = interact_tn(tn, ctx.content+'\n')
    if output:
        await ctx.channel.send(output)
    else:
        await ctx.channel.send('no output for some reason ­ЪциРђЇРЎђ№ИЈ№ИЈ')
Ejemplo n.º 17
0
    def getDataList(self, num=5):
        print('爬取中...')
        #将浏览器的request header和response header的字段复制过来
        headers = {
            'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36",
            'Host': 'www.kuaidaili.com',
            'Referer': 'https://www.kuaidaili.com/free/inha'
        }
        totalList = []  #爬取到的所有的ip
        ableList = []   #爬取到的有效的ip
        unableList = [] #爬取到的无效的ip
        page = 1   #为保证能爬取到足够多的有效代理,这里设置最大爬取页数

        #至少要爬取到num个有效的免费ip地址
        while len(ableList) < num:
            self.url = self.baseUrl + str(page)
            req = requests.get(self.url, headers=headers)
            html_doc = BeautifulSoup(req.text, 'html.parser')
            lists = html_doc.select('.table.table-bordered.table-striped tbody tr')
            print('数据分析中,请稍等...')
            for tr in lists:
                self.tr = tr
                ip = self.getText(0) + ':' + self.getText(1)
                obj = {
                    'ip': ip,
                    'anonymous': self.getText(2),
                    'type': self.getText(3),
                    'address': self.getText(4),
                    'responseTime':self.getText(5),
                    'finalVerifyTime': self.getText(6),
                }
                totalList.append(obj)
                try:
                    Telnet(self.getText(0), self.getText(1),timeout=10)#timeout的只是在初始化socket连接时起作用,而一旦连接成功后如果出现等待那就不会起作用了
                    ableList.append(obj)
                    print('ableList:', ableList, len(ableList))
                except:
                    unableList.append(obj)
            page = page + 1
        self.totalList = totalList
        self.ableList = ableList
        self.unableList = unableList
        return ableList
Ejemplo n.º 18
0
    def player_joined_check(self):
        status = self.server_status()[1]
        sts_msg = self.server_status()[0]
        if status <= 0:
            msg = "サーバが正常に起動していません。\n" + sts_msg
            return msg
        login_status = []
        member = ""
        with Telnet('localhost', 8081) as tn:
            tn.write(b'lp\n')
            time.sleep(1)
            tn.write(b'exit\n')
            login_mem = tn.read_all().decode().split("\n")[16:-1]

            for i in range(len(login_mem)):
                login_status += [login_mem[i].replace('\r', '\n')]
                member += login_status[i]

        return member[:-1]
Ejemplo n.º 19
0
 def telnet_to_device(self):
     # Create telnet connection to host
     print("\n---Device Connection---")
     self.input_host()
     print("Attempting connection to " + self.host + "...")
     try:
         self.connection = Telnet(self.host,
                                  self.PORT,
                                  timeout=self.CONNECT_TIMEOUT)
         if self.TELNET_DEBUG_MODE:
             # Print extra console output
             self.connection.set_debuglevel(1)
     except (socket.gaierror, socket.timeout) as e:
         # Kill connection when it fails
         print("Connection to host failed:", e)
         self.host = ""
         self.connection = None
         return
     print("Connection Succeeded!")
Ejemplo n.º 20
0
 def test_pipelined_request(self):
     two_requests = "GET /foo.html HTTP/1.1\r\nHost: bar\r\n\r\nGET /good_cat HTTP/1.1\r\nHost: baz\r\n\r\n"
     expected = (
         b"HTTP/1.1 200 OK\r\nServer: TritonHTTP/0.1\r\nContent-Length: 37\r\n"
         +
         b"Content-Type: text/html\r\nLast-Modified: Sat, 21 Jan 2017 23:59:32 GMT\r\n\r\n"
         + b"<h1> hi</h1>\n<p>\nthis is things\n</p>\n" +
         b"HTTP/1.1 200 OK\r\nServer: TritonHTTP/0.1\r\nContent-Length: 5\r\n"
         +
         b"Content-Type: text/plain\r\nLast-Modified: Sat, 21 Jan 2017 23:56:17 GMT\r\n\r\nmeow\n"
     )
     try:
         conn = Telnet(self.host, self.port)
         conn.write(two_requests.encode("UTF-8"))
         responses = conn.read_until(b"kldjsflskdfjsdlkfj",
                                     timeout=SLEEP_TIMEOUT)
         self.assertEqual(expected, responses)
     finally:
         conn.close()
Ejemplo n.º 21
0
def connect():
    server = 'localhost'
    port = 4212
    timeout = 5
    password = "******"
    global telnet
    telnet = Telnet()
    telnet.open(server, port, timeout)

    result = telnet.expect([r"VLC media player ([\d.]+)".encode("utf-8")])

    telnet.read_until("Password: "******"utf-8"))
    telnet.write(password.encode("utf-8"))
    telnet.write("\n".encode("utf-8"))

    result = telnet.expect(["Password: "******"utf-8"), ">".encode("utf-8")])

    if "Welcome" in str(result[2]):
        print("Connection Succesful")
Ejemplo n.º 22
0
def blockIP():
    filename = sys.argv[1]

    packets_list = []
    path = 'data_testcsv/' + filename
    with open(path, newline='') as csvfile:
        rows = csv.reader(csvfile, delimiter=',')
        for row in rows:
            packets_list.append(row)

    ip = {}
    for i in range(len(packets_list)):
        if i == 0:
            continue
        #print (packets_list[i][3])
        if packets_list[i][3] != "140.168.0.3":
            if check_ip(ip, packets_list[i][3]):
                ip[packets_list[i][3]] += 1
            else:
                ip[packets_list[i][3]] = 1

    block_ip = ""
    # how to block ip below

    # block in router
    tn = Telnet("140.168.0.1")
    tn.read_until(b"Username")
    tn.write("root".encode('ascii') + b"\r\n")
    tn.read_until(b"Password:"******"123456".encode('ascii') + b"\r\n")
    tn.write("conf t".encode('ascii') + b"\r\n")
    tn.write("access-list 10 deny ".encode('ascii'))

    # for loop ip block
    tn.write(block_ip.encode('ascii') + b"\r\n")

    tn.write("access-list 10 permit any".encode('ascii') + b"\r\n")
    tn.write("interface f0/0".encode('ascii') + b"\r\n")
    tn.write("ip access-group 10 in".encode('ascii') + b"\r\n")
    tn.write("exit".encode('ascii') + b"\r\n")
    tn.write("exit".encode('ascii') + b"\r\n")
    tn.write("exit".encode('ascii') + b"\r\n")
    tn.read_all()
Ejemplo n.º 23
0
def find_hnbs(hnbgw, interval=30):
    telnet = Telnet(hnbgw, '4261')
    time.sleep(1)
    telnet.read_very_eager()
    telnet.write(b'show hnb all\n')
    HNB = re.compile(r'^HNB \(r=(?P<ip>.*):\d*\<-\>.*')
    hnbs = {}
    time.sleep(1)
    data = telnet.read_very_eager().decode('utf-8')
    data = data.replace('\r', '')
    lines = data.splitlines()
    for line in lines:
        result = HNB.match(line)
        if result is None:
            continue
        ipaddr = result.group('ip')
        hnb_id = ipaddr.split('.')[-1]
        hnbs[hnb_id] = ipaddr
    return hnbs
Ejemplo n.º 24
0
    def _infoTelnet(self, command, port = None):
        # TODO: Handle socket failures
        if port == None:
            port = self.port
        try:
            self.sock == self.sock # does self.sock exist?
        except:
            self.sock = Telnet(self.ip, port)

        self.sock.write("%s\n"%command)

        starttime = time()
        result = ""
        while not result:
            result = self.sock.read_very_eager().strip()
            if starttime + self._timeout < time():
                # TODO: rasie appropriate exception
                raise IOError("Could not connect to node %s"%self.ip)
        return result
Ejemplo n.º 25
0
def openvpn_status():
	try:
		with Telnet('localhost', 7505) as tn:
			for i in range(200):
				try:
					tn.write(state_str)
					success_str = tn.read_until(b'SUCCESS', 0.1).decode('ascii')
					print('success_str')
					print(success_str)
					if 'SUCCESS' in success_str:
						return True

				except EOFError:
					return restart_openvpn()

		return restart_openvpn()
	except ConnectionRefusedError:
		print('openvpn.py: 64')
		return False
Ejemplo n.º 26
0
Archivo: VSCD.py Proyecto: asaba/RFLab
 def __init__(self, host, port, device_address=65):
     port = eval(port)
     self._vscd = Telnet(host, port)
     self._socket = (host, port)
     self._address = device_address
     sleep(WAIT_AFTER_CONNECT)
     self._receive()
     # for some reason first send-receive does not work, so dummy
     tmp = self._last_read
     self.valid_command = [
         "EQAA", "EQAB", "EQAC", "ZET", "BSA", "FE", "FA", "FB", "TA", "TB",
         "QA", "QB", "ID", "VW", "VF", "ZO", "ZA", "DA", "ZR", "ZC", "ZI",
         "ZB", "ZW", "ZP", "ZT", "ZD", "ZG", "ZJ", "ZF", "EA", "EE", "EC",
         "QT", "SA", "QS", "G", "J", "A", "B", "F", "I", "T", "C", "M", "U",
         "X", "Y", "Q", "N", "O", "S", "R"
     ]
     self.error_code = ["a", "b", "c", "g"]
     self._connected = True
     self._last_read = tmp
Ejemplo n.º 27
0
    def __init__(self, host, user=None, passwd=None):
        self.connected = False
        self.loggedin = False
        self.user = user
        self.passwd = passwd

        self.conn = Telnet(host, self.port, self.timeout)
        self.connected = True

        self.conn.read_until("login: "******"{0}\n".format(self.user))

        while not self.loggedin:
            self.conn.read_until("Password: "******"{0}\n".format(self.passwd))

            index, _, _ = self.conn.expect([r'\$ ', r'Password'])
            if index == 0:
                self.loggedin = True
Ejemplo n.º 28
0
    def __all_set(self, begin, end):
        #tel = null
        try:
            print("telnet...")
            tel = Telnet(self.ip)
            tel.read_until('Username:'******'\n')
            tel.read_until('Password:'******'\n')
            tel.read_until('ROS>')
            tel.write('en\n')
            tel.read_until('ROS#')

            # set apn和net
            tel.write('^config\n')
            tel.read_until('ROS(config)#')
            for port in range(begin, end + 1):
                print('set port ' + str(port))
                #设置APN
                tel.write('mobile cmd at ' + str(port) +
                          ' at+qicsgp=1,1,"","uno.au-net.ne.jp","123456",1\n')
                tel.read_until('ROS(config)#')
                time.sleep(0.1)
                #设置NET
                tel.write('mobile cmd at ' + str(port) +
                          ' at+cgdcont=1,"IPV4V6","uno.au-net.ne.jp"\n')
                tel.read_until('ROS(config)#')
                #设置NET
                tel.write('mobile cmd at ' + str(port) + ' at+qcfg="ims",1\n')
                tel.read_until('ROS(config)#')

            tel.write('ex\n')
            tel.read_until('ROS#')

            tel.write('^ada\n')
            tel.read_until('ROS(ada)#')

        except:
            print("exception...")
        finally:
            print("all set...")
            tel.close()
Ejemplo n.º 29
0
def reset_board(args):
    success = False

    try:
        tn = Telnet(args.ip, timeout=5)
        print("Connected via Telnet, trying to login now")

        if b'Login as:' in tn.read_until(b"Login as:", timeout=5):
            tn.write(bytes(args.user, 'ascii') + b"\r\n")

            if b'Password:'******'s telnet server
                time.sleep(0.2)
                tn.write(bytes(args.password, 'ascii') + b"\r\n")

                if b'Type "help()" for more information.' in tn.read_until(
                        b'Type "help()" for more information.', timeout=5):
                    print("Telnet login succeeded")
                    tn.write(b'\r\x03\x03'
                             )  # ctrl-C twice: interrupt any running program
                    time.sleep(1)
                    tn.write(b'\r\x02')  # ctrl-B: enter friendly REPL
                    if b'Type "help()" for more information.' in tn.read_until(
                            b'Type "help()" for more information.', timeout=5):
                        tn.write(b"import pyb\r\n")
                        tn.write(b"pyb.reset()\r\n")
                        time.sleep(1)
                        print("Reset performed")
                        success = True
                    else:
                        print("Error: cannot enter friendly REPL")
                else:
                    print("Error: telnet login failed")

    except Exception as e:
        print_exception(e)
    finally:
        try:
            tn.close()
        except Exception as e:
            pass
        return success
Ejemplo n.º 30
0
def get_cluster_info(host, port):
    """
    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) != 2 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)
    res = client.read_until(b'\n\r\nEND\r\n')
    client.close()
    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('{}:{}'.format(smart_text(ip or host),
                                        smart_text(port)))
    except ValueError:
        raise WrongProtocolData(cmd, res)
    return {'version': version, 'nodes': nodes}