def tlnt_connect(doc, timeout): print2('connecting') tn = Telnet(doc['server']) print2('sending username') s = tn.read_until(b'Username: '******'login'] + '\n\r' tn.write(cmd.encode('ascii')) print2('sending password') s = tn.read_until(b'Password: '******'password'] + '\n\r' tn.write(cmd.encode('ascii')) t = tn.expect([b'\r\n/', b'\r\nUser authorization failure\r\n']) if t[0] in [1, -1]: tn.close() return s = t[2] s = s.decode('ascii') i1 = s.find('AT') i2 = s.find('/') dd = s[i1+3:i2] hh = s[i2+1:i2+3] doc['dd2'] = dd doc['hh2'] = hh hhh = 24*int(dd) + int(hh) hhh -= int(doc['hh']) if hhh < 0: hhh = 0 doc['dd1'] = '%d' % (hhh/24) doc['hh1'] = '%d' % (hhh%24) return tn
def __init__ (self, port=monBase): # 1st usable IP = monBase +2 # host='localhost', Telnet.__init__(self) self.host = 'localhost' self.port = port self.history = History() #self.rlock = RLock() # from man kvm: "Only one TCP connection at a time is accepted" if self.trace: self.set_debuglevel(1)
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
def cmd(self, word): """Connect and send a 4letter command to Zookeeper. """ # Zookeeper closes the socket after every command, so we must reconnect every time. tn = Telnet(self.host, self.port, self.timeout) tn.write('{}\n'.format(word)) return tn.read_all()
def connectToServer(hostIP = "10.10.100.254", port = 8899): HOST = hostIP #Host IP Address PORT = port #Host port number pingStr = "ping "+HOST #Attempt to ping host if (os.system(pingStr)==0): #Host able to be pinged print "Robot found...", #Comma prevents printed line from wrapping try: #Attempt to connect to remote host tn = Telnet(host = HOST, port = PORT) print "Connected!" except Exception as E: #Failed connection print "Connection failed!" raise E else: #Host not found print "Host not found" raise ValueError('Could not connect to a host') print "Transmitting..." cmdSet = [['SPL','!C'], #Clear buffer ['SPL','!?'], #Request command buffer ['SPL','!N'], #Request ID ['CMD','1',50,51,52], #Transmit commands ['CMD','A',98,99,100], ['SPL','!?'], #Request command buffer ['SPL','!N']] #Request ID cmdSetStr = cmdSet2Str(cmdSet) tn.write(cmdSetStr) sleep(0.5) #Wait after transmitting return tn
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
def getchannellist(host="192.168.1.23", port=6419): t = Telnet(host, port) t.write("LSTE\nQUIT\n") items = t.read_all().split("\r\n") #lines = filter(lambda s: s.startswith("250"), lines) # items = map(lambda s: s[4:].split(":"), lines) return items
def __init__(self, force_ssl=True, telnet_tls=True, **kwargs): """ Called just like telnetlib.Telnet(), with these extra options: force_ssl - If True, force SSL negotiation as soon as connected. Defaults to True. telnet_tls - If true, allow TELNET TLS negotiation after non-ssl connection. Defaults to True. Also accepts args to ssl.wrap_socket() If force_ssl is True, plaintext connections aren't allowed. If force_ssl is False, and telnet_tls is True, the connection will be plaintext until the server negotiates TLS, at which time the connection will be secured. If both are False, the connection will be plaintext. """ self.in_tls_wait = False self.tls_write_buffer = b'' self.secure = False self.force_ssl = force_ssl self.allow_telnet_tls = telnet_tls self.ssltelnet_callback = None ssl_argnames = { 'keyfile', 'certfile', 'cert_reqs', 'ssl_version', 'ca_certs', 'suppress_ragged_eofs', 'ciphers', } self.ssl_args = {k: v for k, v in kwargs.items() if k in ssl_argnames} telnet_args = {k: v for k, v in kwargs.items() if k not in ssl_argnames} Telnet.__init__(self, **telnet_args) Telnet.set_option_negotiation_callback(self, self._ssltelnet_opt_cb)
class MitutoyoConnection(object): # telnet connection to terminal server host = "10.1.1.35" port = 10001 def __init__(self): try: self.telnet = Telnet(self.host, self.port) except: print("Cannot connect to mitutoyo host!! Check connections and try again or use manual entry") self.telnet = None def queryGauges(self): radialFloats = [] for gaugeNum in range(1,6): self.telnet.write("D0%i\r\n"%gaugeNum) gaugeOutput = self.telnet.read_until("\r", 1) try: gauge, val = gaugeOutput.strip().split(":") gauge = int(gauge) val = float(val) assert gauge == gaugeNum print("gauge %i: %.4f"%(gauge, val)) except: raise RuntimeError("Failed to parse gauge %i output: %s"%(gaugeNum, gaugeOutput)) radialFloats.append(val) return radialFloats
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"
class Session: def __init__(self, host, port, username, password): self.telnet = Telnet(host, port, 5) self.read_until("Login id:") self.write(username +"\n") self.read_until("Password:"******"\n") self.read_until("Welcome root.HELP for a list of commands") def read_until(self, text): self.telnet.read_until(text.encode('ascii'), 5) def write(self, text): self.telnet.write(text.encode('ascii')) def is_user_registered(self, username): self.write("verify %s\n" % username) res = self.telnet.expect([b"exists", b"does not exist"]) return res[0] == 0 def create_user(self, username, password): self.write("adduser %s %s\n" % (username, password)) self.read_until("User %s added" % username) def reset_password(self, username, password): self.write("setpassword %s %s\n" % (username, password)) self.read_until("Password for %s reset" % username) def quit(self): self.write("quit\n")
def testWelcomeMessage(self): """On connecting the server sends a 220 response with a welcome message.""" client = Telnet('localhost', 1025) self.assertEqual(client.read_some(), '220 test node.js smtpevent server 0.0.2\r\n' ) client.close()
def main(): usage = "usage: %prog [options] GRIDFTP_SERVER_FQDN GRIDFTP_SERVER_PORT" parser = OptionParser(usage) parser.add_option('--timeout', type='int', default=5, help="Telnet timeout value in seconds") (options, args) = parser.parse_args() if len(args) != 2: raise Exception('Number Of Args != 2') gridftp_server_name = args[0] gridftp_server_port = args[1] try: gridftp_connection = Telnet(gridftp_server_name, gridftp_server_port, options.timeout) output = gridftp_connection.read_until('ready.', options.timeout) for txt in ['220', 'GridFTP Server', 'ready']: if txt not in output: raise Exception() gridftp_connection.close() print 'PYGLIDEIN_RESOURCE_GRIDFTP=True' print '- update:true' except: print 'PYGLIDEIN_RESOURCE_GRIDFTP=False' print '- update:true'
def get(host="localhost", port=4242): tel = Telnet(host, port) _get(tel) tel.write("content.location.href") result = _get(tel) tel.close() return result[0].strip('"')
class voip: only_number = re.compile('.*RING;\d*;(\d*);.*') fritzbox = None telnet = None def __init__(self, fritzbox="192.168.178.1"): self.fritzbox = fritzbox nc = notifier() self.connect() telnet = self.telnet logging.info('Connected to Telnet: {0}'.format(str(telnet))) while True: try: logging.info('Waiting for nother event') try: data = telnet.read_until('POTS;', 300) # maybe read while 1 and then do except EOFError: logging.warning('Lost connection to telnet server') self.reconnect() number = '\n'.join(self.only_number.findall(data)) if number: logging.info('The number extracted form: {0} is: {1}'.format(data, number)) nc.notify("Incomming call", "From: {0}".format(number)) except KeyboardInterrupt: logging.info('KeyboardInterrupt') self.delete() exit() def connect(self): fritzbox = self.fritzbox for i in range(3): try: self.telnet = Telnet(fritzbox, '1012', 60) logging.info('Telnet connection to {0} succseed'.format(fritzbox)) break except: message = 'Telnet connection #{0} failed'.format(i) if i >= 3: logging.Waiting(message) else: logging.info(message) return 0 def reconnect(self): self.telnet.close() self.connect() def delete(self): logging.info('Clearing Telnet session up') self.telnet.close()
def killSonar( self ): tmpSession = Telnet( '192.168.1.1' ) tmpSession.write('killall %s\n' % SONAR_EXE.split('/')[-1]) while 1: line = self.session.read_until('\n', timeout=1.0).strip() if line == '#': break tmpSession.close()
def restart_procserv_ioc(ioc_port=29200): """ send a Ctrl-C to a procServ ioc running on localhost """ tn = Telnet('localhost', ioc_port) tn.write('\x03') tn.write('\n') time.sleep(3)
def update(self): """Get the latest data from hhtemp running as daemon.""" try: connection = Telnet(host=self.host, port=self.port, timeout=DEFAULT_TIMEOUT) self.data = connection.read_all().decode("ascii") except ConnectionRefusedError: _LOGGER.error("HDDTemp is not available at %s:%s", self.host, self.port) self.data = None
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()
def __init__(self,host,port): try: Telnet.__init__(self,host,port) except: print "Cannot connect to:", host, port self.prompt = [] self.prompt.append( re.compile('/[^>]*> ') ) self.timeout = 2
def __init__(self, stream, logfile): Telnet.__init__(self, host=None) self.stream = stream self.logfile = logfile self.eof = 0 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(stream)
def Expect(self,pat , wait=2, nowait=False): self.fExpecting=True if wait==None: wait=0.5 else: wait = float(wait) found =None m =None if not nowait: if not self.fInteractionMode: output =self.expect(["%s"%(pat)],float(wait)) self.output=output[2] m =sre.search('%s'%(pat), self.output, sre.M|sre.DOTALL) else: interval=0.1 counter =0 max_counter=round(float(wait)/interval)+1 interactionpat = '(%s)(.*)'%pat while counter<max_counter: counter+=1 m =sre.search(interactionpat,self.InteractionBuffer,sre.M|sre.DOTALL) if m: self.InteractionMatch=m.group(0) self.InteractionBuffer=m.group(1)#.decode("utf-8") break time.sleep(interval) else: m = sre.search(pat,self.output, sre.M|sre.DOTALL) self.seslog.flush() self.fExpecting=False if not m: raise Exception('Expect("%s", %f) Failed'%(pat,float(wait))) self.match = m.group() global reSessionClosed mSesClosed= sre.search(reSessionClosed,self.output) isalive = self.isalive() if (self.Connect2SUTDone): if (mSesClosed): command = self.attrs['CMD'] self.error("Session(%s) has been closed by remote host!"%(self.sutname)) if command.find('telnet')!=-1: host="" port=23 args = command.split(' ') if len(args)==2: host = args[1] elif len(args)==3: host= args [1] port = args[2] spawn.__init__(self, host, port) self.set_debuglevel(1) self.Login2SUT() return self.output
def _makeRequest(self, verb, **dikt): """Send a request to the server NOTE: does not validate the content of responses""" # Connect via telnet to the server connection = Telnet(self.host, self.port) # Receive the welcome message # Example: MaverickChessServer/1.0a1 WAITING_FOR_REQUEST welcome = connection.read_until("\r\n", MaverickClient.TIMEOUT) # Validate the welcome message err = None if welcome[:19] != "MaverickChessServer": err = "bad_name" elif welcome[19] != "/": err = "bad_header_separator" else: (version, sep, status) = welcome[20:].partition(" ") if version != __version__: err = "incompatible_version" elif sep != " ": err = "bad_separator" elif status != "WAITING_FOR_REQUEST\r\n": err = "bad_status" if err != None: MaverickClient._logger.error("Invalid server welcome (%s): %s", err, welcome) raise MaverickClientException("Invalid server welcome") # Send the request requestStr = "{0} {1}\r\n".format(verb, json.dumps(dikt, encoding="utf-8")) connection.write(requestStr) # Receive the response response = connection.read_until("\n", MaverickClient.TIMEOUT) # Parse the response and deal with it accordingly statusString, _, value = response.partition(" ") if statusString == "SUCCESS": try: result = json.loads(value, object_hook=_asciify_json_dict) except ValueError: raise MaverickClientException("Invalid JSON in response") return result elif statusString == "ERROR": errMsg = value.rstrip() # Trim trailing new line MaverickClient._logger.debug("Received error response: %s", errMsg) raise MaverickClientException(errMsg) else: msg = "Invalid status string received" MaverickClient._logger.error(msg) raise MaverickClientException(msg)
def createNewConn(self): ''' Connects to a digiport device and logs in ''' portObj = Telnet(self.ip) portObj.read_until("login: "******"\n") portObj.write(self.password + "\n") return portObj
def Login_to_device(self): telnet_conn=Telnet(self.ip_addr,self.TELNET_PORT,self.TELNET_TIMEOUT) telnet_conn.read_until('sername:') telnet_conn.write(self.username + '\n') telnet_conn.read_until('assword:') telnet_conn.write(self.password + '\n') time.sleep(1) output=telnet_conn.read_very_eager() return telnet_conn,output
def episode_iv(): hst = 'towel.blinkenlights.nl' from telnetlib import Telnet t = Telnet(hst) while True: buf = t.read_until('mesfesses', 0.1) print buf
def __init__(self, host_port_timeout, secret=None, **kwargs): if isinstance(host_port_timeout, basestring): host_port_timeout = host_port_timeout.split(':') Telnet.__init__(self, *host_port_timeout) (status, length), content = self._read() if status == 107 and secret is not None: self.auth(secret, content) elif status != 200: logging.error('Connecting failed with status: %i' % status)
def test_rifidi_server(self): self.port = '2020' self.host = 'localhost' telnet = Telnet(self.host, self.port) #telnet.write('\r\n') #expected = '\r\nosgi> ' actual = telnet.read_eager() #self.assertEqual(expected, actual) expected = {} expected['Rifidi App: Diagnostic:GPIO (STOPPED)'] = False expected['Rifidi App: Diagnostic:Serial (STOPPED)'] = False expected['Rifidi App: Diagnostic:Tags (STARTED)'] = False expected['Rifidi App: Diagnostic:TagGenerator (STARTED)'] = False expected['Rifidi App: AppService:ReadZones (STARTED)'] = False expected['Rifidi App: AppService:SensorStatus (STARTED)'] = False expected['Rifidi App: AppService:UniqueTagInterval (STARTED)'] = False expected['Rifidi App: AppService:StableSet (STARTED)'] = False expected['Rifidi App: AppService:UniqueTagBatchInterval (STARTED)'] = False expected['Rifidi App: Monitoring:ReadZones (STARTED)'] = False expected['Rifidi App: Monitoring:Tags (STARTED)'] = False expected['Rifidi App: Monitoring:SensorStatus (STARTED)'] = False expected['Rifidi App: Ambient:Association (STARTED)'] = False expected['Rifidi App: Ambient:DBApp (STARTED)'] = False expected['Rifidi App: Ambient:MessageReceiver (STARTED)'] = False expected['Rifidi App: Ambient:SensorDownAlert (STARTED)'] = False expected['Rifidi App: Ambient:TagCountApp (STARTED)'] = False expected['Rifidi App: Ambient:StationStatusAlert (STARTED)'] = False expected['Rifidi App: Ambient:Grouping (STARTED)'] = False expected['Rifidi App: Ambient:TagReadApp (STARTED)'] = False expected['Rifidi App: Ambient:Receiving (STARTED)'] = False expected['Rifidi App: Ambient:Portal (STOPPED)'] = False expected['Rifidi App: Ambient:ReceiveTest (STARTED)'] = False telnet.write('apps\r\n') time.sleep(2.5) done = False while not done: value = '' value = telnet.read_eager() actual += value if value == '': done = True actual = actual.replace('osgi>', '') actual = re.sub(r'[0-9]+:', '', actual, count=0) actual = actual.split('\r\n') for i in range(0, actual.__len__()-1): actual[i] = re.sub(r'^ ', '', actual[i]) for i in actual: if i in expected: expected[i] = True for i in expected.keys(): self.assertTrue(i)
def onJoin(self, details): namespace = self.app_config['namespace'] do_raw = self.app_config['raw'].lower()=='true' firebase_server = firebase.FirebaseApplication('https://amber-fire-3917.firebaseio.com') def send(key,d): return self.publish(namespace+u'.queue.'+key,d) and 1 or 0 def blink(d): return send('blink',d['blinkStrength']) def data(d): return send('data', [d['eSense']['attention'] ,d['eSense']['meditation'] ,d['eegPower']['lowAlpha'] ,d['eegPower']['highAlpha'] ,d['eegPower']['lowBeta'] ,d['eegPower']['highBeta'] ,d['eegPower']['lowGamma'] ,d['eegPower']['highGamma'] ,d['eegPower']['delta'] ,d['eegPower']['theta'] ]) def raw(d): return send('raw',d['rawEeg']) def sendany(d): print(d) if 'blinkStrength' in d: return blink(d) if 'eegPower' in d: return data(d) if 'rawEeg' in d: return raw(d) return None if self.app_config['debug'].lower()=='true': print('debug mode.') counter = 0 while True: send('debug', counter) #print("Published event.") counter += 1 yield sleep(1) else: tn = Telnet('localhost',13854) tn.write('{"enableRawOutput": %s, "format": "Json"}' % (['false','true'][do_raw],)) i = tn.read_until('\r') while True: # ret = sendany(json.loads(tn.read_until('\r'))) firebase_server.post('/mindwave', json.loads(tn.read_until('\r'))) yield sleep(0.001)
def _create_command_client(self): self._command_client = Telnet(host=self.hostname, port=self.port) self.schandlerid = int( _receive_message(self._command_client).args['schandlerid'])
sys.exit(-1) asteroid = int(sys.argv[1]) print "Asteroid: " print asteroid print "output filename: " input = sys.argv[2] output = sys.argv[3] outf = open(output, "w") print output #file=glob.glob(input) f = open(input, 'r') print "processing" print f tn = Telnet('ssd.jpl.nasa.gov', 6775) for line in f: time = float(line) print "Processing time " print line #fits_open=pyfits.open(f) #hdu=fits_open[0] #time=hdu.header['MJD-OBS']+2400000.5 V2 = get_horizons(tn, asteroid, time) #Asteroid direction LT = V2[3] V1 = get_horizons_sun(tn, 10, LT) #Sun direction from Earth V3 = V1[0:3] - V2[0:3] #Points from asteroid to Sun V2 = -V2[0:3] #Points from asteroid to Earth outf.write(str(time) + " ") V3.tofile(outf, sep=" ")
def _create_event_client(self): self._event_client = Telnet(host=self.hostname, port=self.port) _receive_message(self._event_client) self._event_thread = self.ReceiveThread(self._event_client) self._event_thread.start()
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
class bluefors: def __init__(self): self.LogPath = Path(r'\\BLUEFORSAS\BlueLogs') self.Days = listdir(self.LogPath) def whichday(self): total = len(self.Days) for i, day in enumerate(self.Days): print("%s. %s" % (i + 1, day)) while True: try: k = int( input("Which day would you like to check out (1-%s): " % total)) if k - 1 in range(total): break except (ValueError): print("Bad index. Please use numeric!") return k - 1 def selectday(self, index): try: self.Date = self.Days[index] print("Date selected: %s" % self.Date) except (ValueError): print("index might be out of range") pass def pressurelog(self, Channel): LogFile = self.LogPath / self.Date / ("maxigauge " + self.Date + ".log") with open(LogFile, 'r') as L: L = L.read() Plog = L.split('\n')[:-1] Plog = [x for x in Plog if ',,' not in x] #filter-out bad logs t = [ datetime.strptime(x.split("CH")[0][:-1].split(',')[1], '%H:%M:%S') for x in Plog ] startime = t[0].strftime('%H:%M:%S') t = [(x - t[0]).total_seconds() / 3600 for x in t] P = [float(x.split("CH")[Channel][14:21]) for x in Plog] P_stat = [int(x.split("CH")[Channel][11]) for x in Plog] return startime, t, P, P_stat def temperaturelog(self, Channel, Unit='K'): LogFile = self.LogPath / self.Date / ("CH%s T " % Channel + self.Date + ".log") with open(LogFile, 'r') as L: L = L.read() Tlog = list([x.split(',') for x in L.split('\n')[:-1]]) t, T = [datetime.strptime(x[1], '%H:%M:%S') for x in Tlog], [float(x[2]) for x in Tlog] startime = t[0].strftime('%H:%M:%S') t = [(x - t[0]).total_seconds() / 3600 for x in t] if Unit.upper() == 'C': T = [x - 273 for x in T] return startime, t, T 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!") def gauge(self, Channel): self.connect.write(("mgstatus %s\n" % Channel).encode('ascii')) output = self.connect.read_until(b"\r\n").decode('ascii').replace( '\r\n', '').split(": ") return output[1] def close(self): self.connect.write("exit\n".encode('ascii')) print("Dilution's server disconnected!")
''' @author: patir ''' from telnetlib import Telnet # examples of telnet connections PORT = 12345 HOST = '54.209.5.48' # creating connection tn = Telnet(HOST, PORT) # reading input msg_in2 = tn.read_all().dec_msg() tn.read_until(b'psifer text: ') # writing outputs # tn.write(msg.encode() + b'\n')
def execute(conn: telnetlib.Telnet, line: str) -> None: """ executes an econ command. """ cmd = f"{line}\n".encode('utf-8') conn.write(cmd)
def telnet_to_the_server(host, port=22): with Telnet(host, port) as tn: tn.interact()
#!/usr/bin/env python3 from requests import Session from telnetlib import Telnet import sys from binascii import hexlify from random import choices from time import sleep #TEAM_IP = sys.argv[1] ip_idx = 0 ips = ["10.0.1.1", "10.0.2.1", "10.0.4.1", "10.0.5.1"] tn = Telnet("10.0.0.2", 1337) while True: BASEURL = f"http://{ips[ip_idx%4]}:8001" ip_idx += 1 s = Session() r = s.get(BASEURL + "/api/gamesession/Listrecent?take=100&skip=0") res = r.json() randomunicode = "ÄÖßÜ" def login(s, user): rando_pw = ''.join(choices(randomunicode, k=128)) r = s.post(BASEURL + "/api/account/login", data={ "userName": user, 'password': rando_pw }) #print(r) #assert r.status_code == 200 def gettoken(s):
www_port = int(arg) except ValueError: print_help() # Initialise notifications. pynotify.init('squeezebox-notify') notification = pynotify.Notification('Squeezebox Notify', 'Connecting to %s' % (server if port == 9090 else ('%s:%i' % (server, port,))), '/home/mmm/kode/squeezebox-notify/resources/squeezebox.jpg') notification.show() # Compile a regex for player related notifications, which are identified by a MAC address and then some. player_pattern = re.compile('^(([0-9a-f]{2}%3A){5}[0-9a-f]{2}) (.+)') # Start telnet clients (one a as listener, another to fetch info). listener = Telnet() listener.open(server, port) fetcher = Telnet() fetcher.open(server, port) # Authenticate, if necessary. if username and password: listener.write('login %s %s\n' % ( urllib.quote(username), urllib.quote(password), )) listener.read_until('\n') fetcher.write('login %s %s\n' % ( urllib.quote(username), urllib.quote(password), )) fetcher.read_until('\n')
from random import randint, random from time import sleep from telnetlib import Telnet def randcolor(a, b, chance_of_low=0): return hex(randint(a, b))[2:].zfill(2) with Telnet('192.168.0.109', 1337) as tn: tn.write(b"SIZE\n") size = tn.read_until(b'\n').decode()[:-1].split(' ') w, h = int(size[1]), int(size[2]) def rand_point(): x, y = randint(0, w), randint(round(h - (random() * 300)), h) r = randcolor(0x4F, 0xFF) # y lower => better chance of 0x7F g = randcolor(0X00, 0xAA) # y lower => better chance of 0x00 return x, y, f"{r}{g}00" # Clean bottom: for x in range(w): for y in range(h - 100, h): tn.write(f'PX {x} {y} 000000\n'.encode()) while True: x, y, color = rand_point() tn.write(f'PX {x} {y} {color}\n'.encode()) sleep(0.0003)
def _info_loader_run(self): self.debug("Update parent info table") telnet = Telnet(self.host, 4901) telnet.read_until(b'Lumi_Z3GatewayHost') telnet.write(b"option print-rx-msgs disable\r\n") telnet.read_until(b'Lumi_Z3GatewayHost') telnet.write(b"plugin device-table print\r\n") raw = telnet.read_until(b'Lumi_Z3GatewayHost').decode() m1 = re.findall(r'\d+ ([A-F0-9]{4}): {2}([A-F0-9]{16}) 0 {2}\w+ (\d+)', raw) telnet.write(b"plugin stack-diagnostics child-table\r\n") raw = telnet.read_until(b'Lumi_Z3GatewayHost').decode() m2 = re.findall(r'\(>\)([A-F0-9]{16})', raw) telnet.write(b"plugin stack-diagnostics neighbor-table\r\n") raw = telnet.read_until(b'Lumi_Z3GatewayHost').decode() m3 = re.findall(r'\(>\)([A-F0-9]{16})', raw) telnet.write(b"plugin concentrator print-table\r\n") raw = telnet.read_until(b'Lumi_Z3GatewayHost').decode() m4 = re.findall(r': (.{16,}) -> 0x0000', raw) m4 = [i.replace('0x', '').split(' -> ') for i in m4] m4 = {i[0]: i[1:] for i in m4} for i in m1: ieee = '0x' + i[1] if ieee not in self.stats: continue nwk = i[0] ago = int(i[2]) type_ = 'device' if i[1] in m2 else 'router' if i[1] in m3 else '-' parent = '0x' + m4[nwk][0] if nwk in m4 else '-' self.stats[ieee]({ 'nwk': '0x' + nwk, 'ago': ago, 'type': type_, 'parent': parent }) self.info_loading = False # one hour later if self.parent_scan_interval > 0: self.info_ts = time.time() + self.parent_scan_interval * 60
def _getresp(self): (i, match, resp) = Telnet.expect(self, self.prompt, self.timeout) # Remove the terminating prompt. # Everything preceding it is the response. return split(resp, '\n')[:-1]
def read_line(conn: telnetlib.Telnet, timeout=None) -> str: """ wait until a line can be read or if the timeout is reached """ line = conn.read_until(b"\n", timeout=timeout) return line.decode('utf-8')[:-1]
def stop(self): fluid = Telnet("localhost", "9988") self.p.terminate() fluid.write("reset\n".encode('ascii')) fluid.write("quit\n".encode('ascii'))
# 创建/连接数据库对象 conn = sqlite3.connect('ip_group.db') # 获取游标 c = conn.cursor() # 读取数据 t = (no, ) c.execute('SELECT ip FROM device_group WHERE groupno = ?', t) rows = c.fetchall() # 关闭连接 conn.close() # 创建一个Telnet对象 tn = Telnet() # 设置调试等级 tn.set_debuglevel(0) # 尝试建立telnet连接 n = 0 for row in rows: ip = row[0] try: tn.open(ip, timeout=10) # 取设备回显, 判断设备类型 DeviceType = tn.expect([], timeout=1)[2].decode('ascii').strip() if re.search(r'>>', DeviceType): # 华为
from telnetlib import Telnet tn = Telnet("crypto.be.ax", 6005) res = tn.read_until(b"(y/n) ") tn.write(b"y\n") word = "" # loops until 7 returns + def looptop(): global word while (True): tn.write(b"7\n") res = tn.read_until(b"> ") if (res.split(b"\n")[0] == b"The qubit measured as +"): break tn.write(b"6\n") res = tn.read_until(b"> ") # loops until 7 returns - def looptom(): global word while (True): tn.write(b"7\n") res = tn.read_until(b"> ") if (res.split(b"\n")[0] == b"The qubit measured as -"): break tn.write(b"6\n") res = tn.read_until(b"> ")
def telnet_host(host_ip, username, password): ''' :param host_ip: 被测设备的管理 :param username: 被测设备登录的用户名 :param password: 被测设备登录的密码 :return: telnet的连接对象或者布尔值 ''' # try: tn = Telnet(host_ip, port=23) #设置调试级别,debuglevel的值越高,得到的调试输出就越多(在sys.stdout上) Telnet.set_debuglevel(tn, debuglevel=1) # except: # cdata_warn('%s 设备telnet连接失败' % host_ip) # return False, # 等待login出现后输入用户名,最多等待5秒 tn.read_until(b'>>User name: ', timeout=5) tn.write(username.encode() + b'\n') # 等待Password出现后输入用户名,最多等待5秒 tn.read_until(b'>>User password: '******'\n') # 延时1秒再收取返回结果,给服务端足够响应时间 time.sleep(1) # 获取登录结果 # read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出 command_result = tn.read_very_eager().decode('utf-8') if 'Login-Time' in command_result: cdata_info('%s 登录成功' % host_ip) tn.read_until(b'OLT>', timeout=2) tn.write('enable'.encode() + b'\n') # self.tn.read_until(b'OLT# ', timeout=10) tn.write('config'.encode() + b'\n') tn.read_until(b'OLT(config)# ', timeout=5) #设置设备一次性返回所有打印 tn.write('vty output show-all '.encode() + b'\n') tn.read_until(b'OLT(config)# ', timeout=5) return tn, True else: cdata_info('%s 登录失败,用户名或密码错误' % host_ip) return False,
def __init__(self, host_port_timeout): if isinstance(host_port_timeout, basestring): host_port_timeout = host_port_timeout.split(':') Telnet.__init__(self, *host_port_timeout)
def interact(s): print("[*] connect to remote") t = Telnet() t.sock = s t.interact()
class client: """ This class opens a connection to the LCD deamon on the specified host and encapsulates all the functions of the LCDd protocol. """ def __init__(self,host="localhost",port=13666): """ Connect to the LCD daemon. Do *not* send "hello" (connect() is used for that). """ from telnetlib import Telnet self.conn=Telnet(host,port) # Various vars that need to be initialized self.state="unconnected" self.server="unknown" self.s_version="unknown" self.proto="unknown" self.type="unknown" self.d_width=0 self.d_height=0 self.c_width=0 self.c_height=0 # A translation table # FIXME: LCDd does char translation since 0.4.3, # this probably should be detected and stuff self.transtable=string.maketrans("µÀÁÂÃÅÈÉÊËÌÍÎÏÐÑÒÓÔÕ×ØÙÚÛÝàáâãåçèéêëìíîïñòóôõøùúûÆæäöüßÄÖÜ\\","äAAAAAEEEEIIIIDNOOOOxOUUUYaaaaaceeeeiiiinooooouuu\341\341\341\357\365\342\341\357\365\315") self.deltable="" for i in range(160,181): self.deltable=self.deltable+chr(i) for i in range(182,192): self.deltable=self.deltable+chr(i) for i in (222,240,247,254,255): self.deltable=self.deltable+chr(i) def send(self,cmd): """ Send "cmd" plus a linefeed to the server. """ try: self.conn.write(cmd+"\n") except: print 'self.conn.write(%s+"\n") failed' % (cmd) def read(self): """ Read very eagerly, but not necessarily a whole line. Return read data. """ return self.conn.read_very_eager() def readl(self): """ Read and return a whole line. May block. """ try: return self.conn.read_until("\n") except: print 'self.conn.read_until("\n") failed' return None def connect(self): """ Send connect message ("hello") to server and return connection message. Also set internal variables that can be read via getinfo(). """ self.send("hello") line=string.strip(self.readl()) try: (self.state,self.server,self.s_version,c,self.proto,self.type,c,self.ds_width,c,self.ds_height,c,self.cs_width,c,self.cs_height)=string.split(line," ") except ValueError: self.ds_width="0" self.ds_height="0" self.cs_width="0" self.cs_height="0" self.d_width=int(self.ds_width) self.d_height=int(self.ds_height) self.c_width=int(self.cs_width) self.c_height=int(self.cs_height) line=line+self.read() return (line) def getinfo(self): """ Print information gathered during connect(). """ print "Connection state:", self.state print "Server type:", self.server print "Server version: ", self.s_version print "Protocol version:", self.proto print "LCD type:", self.type print "Display size: %sx%s (%s)"%(self.d_width,self.d_height,self.d_width*self.d_height) print "Cell size: %sx%s (%s)"%(self.c_width,self.c_height,self.c_width*self.c_height) def client_set(self,id): """ Implement the client_set command, return server answer """ self.send("client_set %s"%id) return self.readl() def screen_add(self,id): """ Implement the screen_add command, return server answer """ self.send("screen_add %s"%id) return self.readl() def screen_del(self,id): """ Implement the screen_del command, return server answer """ self.send("screen_del %s"%id) return self.readl() def screen_set(self,id,params): """ Implement the screen_set command, return server answer """ self.send("screen_set %s %s"%(id,params)) return self.readl() def widget_add(self,id,type,params=""): """ Implement the widget_add command, return server answer """ self.send("widget_add %s %s %s"%(id,type,params)) return self.readl() def widget_set(self,screen,id,data): """ Implement the widget_set command, return server answer """ self.send("widget_set %s %s %s"%(screen,id,data)) return self.readl() def remap(self,str): """ Maps high-bit ascii charactes which often produce kanjii on HD44780 displays to approximations. Returns string with fixed characters. This one is specially tailored to HD44780 displays. Later versions (>=0.4.3) of LCDd do this by themselves. """ ret=string.translate(str,self.transtable,self.deltable) return(ret)
from telnetlib import Telnet import sys if len(sys.argv) < 2: print("usage: ./telnet-brute.py <host> <userlist> <passlist>") userlist = open(sys.argv[2]).read().splitlines() passlist = open(sys.argv[3]).read().splitlines() host = sys.argv[1] port = 2323 print("trying host: ", host) with Telnet(host, port) as tn: for user in userlist: for password in passlist: try: print("tryping user: "******" with password: "******"login: "******"\n") tn.read_until(b"Password: "******"\n") except: tn.write(b"ls\n") tn.write(b"exit\n")
class Msg: def __init__(self, bn, ip, telnetuser, telnetpw): self.login_flag = False self.bn = bn self.ip = ip self.telnetuser = telnetuser self.telnetpw = telnetpw self.tn = Telnet() def login(self): try: self.tn.open(self.ip.encode(), port=23, timeout=3) # 登陆交互 self.tn.write(b'\n') self.tn.expect([b'Username:'******'\n') self.tn.read_until(b'Password:'******'\n') self.tn.read_until(b'>', timeout=2) self.tn.write('enable\n'.encode()) if '#' in self.tn.read_until(b'#', timeout=2).decode("utf8", "ignore"): self.login_flag = True logging.info('%s login 成功', self.ip) else: logging.warning('%s login 失败,非raisecom设备或密码错误' % self.ip) self.logout() return '%s,login 失败,非raisecom设备或密码错误\n' % self.ip except socket.timeout: logging.warning('%s login 失败,设备不在线' % self.ip) return '%s,login 失败,设备不在线\n' % self.ip except EOFError: logging.warning('%s 连接断开,可能会话数已满' % self.ip) return '%s,连接断开,可能会话数已满\n' % self.ip def logout(self): try: self.tn.close() logging.info('%s logout 成功', self.ip) except: logging.warning('%s logout 错误', self.ip) # 检查型号和批次 def mod_bn(self): self.login() if self.login_flag: try: # 读取版本 self.tn.write('show version\n'.encode()) msginfo = self.tn.read_until(b"#", timeout=2).decode( "utf8", "ignore") if self.bn in msginfo: logging.info('%s 批次号为 %s , 不需要修改', self.ip, self.bn) else: self.tn.write('testnode\n'.encode()) self.tn.read_until(b"Password:"******"(test-node)#", timeout=2) self.tn.write(('bn %s\n' % self.bn).encode()) self.tn.read_until(b"(test-node)#", timeout=2) self.tn.write('end\n'.encode()) self.tn.read_until(b"#", timeout=2) self.tn.write('erase startup-config\n'.encode()) self.tn.read_until(b"#", timeout=15) self.tn.write('reboot\n'.encode()) # self.tn.read_until(b"confirm:", timeout=1) sleep(1) self.tn.write(b'y\n') self.tn.read_until(b'#', timeout=5) logging.info('%s 批次号已修改为 %s ,设备自动重启,如果设备没有自动重启,请手动重启设备生效', self.ip, self.bn) self.logout() except: logging.warning('%s 修改批次号错误', self.ip) self.logout()
from bluetooth import * from telnetlib import Telnet server_address = "cc:3d:82:e8:b3:da" port = 1 s = BluetoothSocket(RFCOMM) s.connect((server_address, port)) t = Telnet() t.sock = s t.interact()
#Вам необходимо написать приложение на любом языке программирования, которое будет принимать в качестве аргументов #IP-адрес и порт коммутатора (длину кабеля в котором нужно измерить). #import telnetlib #telnetlibМодуль обеспечивает Telnetкласс , который реализует протокол Telnet. from telnetlib import Telnet #https://docs.python.org/3/library/telnetlib.html для работы с консолью #IP='10.90.90.29' #port='1-5' IP = input("For analistic enter your IP: ") telnet = Telnet(IP) #вводим порт длину кабеля в котором нужно измерить port = input('Enter port : ') #имя пользователя и пароль telnet.read_until(b'UserName') telnet.write(b'\n') telnet.read_until(b'PassWord') telnet.write(b'\n') #пропускаем ненужные строки telnet.read_until(b'#') #формируем команду для консоли cable_diag ports номер_порта mycommand = 'cable_diag ports ' + str(port) + '\n' encod_mycommand = mycommand.encode(encoding='ascii', errors='strict') #print ("Кодированная строка: ", encod_mycommand) telnet.write(encod_mycommand) print(encod_mycommand)
class connection(metaclass=LogBase): def __init__(self, port=""): self.serial = None self.tn = None self.connected = False if port == "": port = self.detect(port) if port == "": try: self.tn = Telnet("192.168.1.1", 5510, 5) self.connected = True except: self.connected = False if port != "": self.serial = serial.Serial(port=port, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1) self.connected = self.serial.is_open def waitforusb(self, vid, pid): timeout = 0 while timeout < 10: for device in self.detectusbdevices(): if device.vid == vid: if device.pid == pid: return True time.sleep(1) timeout += 1 return False def websend(self, url): headers = { 'Referer': 'http://192.168.0.1/index.html', 'Accept-Charset': 'UTF-8' } r = requests.get(url, headers=headers) if b"FACTORY:ok" in r.content or b"success" in r.content: print( f"Detected a ZTE in web mode .... switching mode success (convert back by sending \"AT+ZCDRUN=F\" via AT port)" ) return self.waitforusb(vendor.zte.value, 0x0016) return False def getserialports(self): return [port for port in serial.tools.list_ports.comports()] def detectusbdevices(self): dev = usb.core.find(find_all=True) ids = [deviceclass(cfg.idVendor, cfg.idProduct) for cfg in dev] return ids def detect(self, port): vendortable = { 0x1199: ["Sierra Wireless", 3], 0x2c7c: ["Quectel", 3], 0x19d2: ["ZTE", 2], 0x0846: ["Netgear", 2], 0x413c: ["Telit", 0] } mode = "Unknown" for device in self.detectusbdevices(): if device.vid == vendor.zte.value: if device.pid == 0x0016: print( f"Detected a {vendortable[device.vid][0]} device with pid {hex(device.pid)} in Diag mode" ) mode = "AT" break elif device.pid == 0x1403: print( f"Detected a {vendortable[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=1' #adb url = 'http://192.168.0.1/goform/goform_process?goformId=MODE_SWITCH&switchCmd=FACTORY' if self.websend(url): mode = "AT" break elif device.vid == vendor.telit.value: if device.pid == 0x81d7: print( f"Detected a {vendortable[device.vid][0]} device with pid {hex(device.pid)} in Diag mode" ) print("Sending download mode command") interface = 5 diag = qcdiag(loglevel=self.__logger.level, portconfig=[[0x413c, 0x81d7, interface]]) if diag.connect(): data = diag.hdlc.receive_reply() res = diag.send(b"\x4b\x65\x01\x00") if res[0] == 0x4B: print("Sending download mode succeeded") diag.disconnect() break if mode == "AT" or mode == "Unknown": for port in self.getserialports(): if port.vid in vendortable: portid = port.location[-1:] if int(portid) == vendortable[port.vid][1]: print( f"Detected a {vendortable[port.vid][0]} at interface at: " + port.device) return port.device return "" def readreply(self): info = [] timeout = 0 if self.serial is not None: while True: tmp = self.serial.readline().decode('utf-8').replace( '\r', '').replace('\n', '') if "OK" in tmp: info.append(tmp) return info elif "ERROR" in tmp: return -1 if tmp != "": info.append(tmp) else: timeout += 1 if timeout == 20: break return info def send(self, cmd): if self.tn is not None: self.tn.write(bytes(cmd + "\r", 'utf-8')) time.sleep(0.05) data = "" while True: tmp = self.tn.read_eager() if tmp != b"": data += tmp.strip().decode('utf-8') else: break return data.split("\r\n") elif self.serial is not None: self.serial.write(bytes(cmd + "\r", 'utf-8')) time.sleep(0.05) return self.readreply() def close(self): if self.tn is not None: self.tn.close() self.connected = False if self.serial is not None: self.serial.close() self.connected = False def ati(self): data = {} info = self.send("ATI") if info != -1: for line in info: if "Revision" in line: data["revision"] = line.split(":")[1].strip() if "Model" in line: data["model"] = line.split(":")[1].strip() if "Quectel" in line: data["vendor"] = "Quectel" if "Manufacturer" in line: data["manufacturer"] = line.split(":")[1].strip() if "Sierra Wireless" in data["manufacturer"]: data["vendor"] = "Sierra Wireless" elif "ZTE CORPORATION" in data["manufacturer"]: data["vendor"] = "ZTE" elif "Netgear" in data["manufacturer"]: data["vendor"] = "Netgear" elif "Telit" in data["manufacturer"]: data["vendor"] = "Telit" return data
class TelnetClient(): def __init__(self, addr, port=23): self.addr = addr self.port = port self.tn = None def start(self): self.tn = Telnet(self.addr, self.port) self.history = deque() # user t = self.tn.read_until('login:'******'utf-8')) stdout.write(t) user = stdin.readline() self.tn.write(user) # password t = self.tn.read_until(b'Password: '******'$ ') stdout.write(t) while True: uinput = stdin.readline() if not uinput: break self.history.append(uinput) self.tn.write(uinput) t = self.tn.read_until(b'$ ') stdout.write(t[len(uinput) + 1:]) def cleanup(self): self.tn.close() self.tn = None with open(self.addr + '_history.txt', 'w') as f: f.writelines(self.history)
def _restore_prompt(self, tnconn: telnetlib.Telnet): tnconn.write(b"echo $PS1\n") ps1_out = tnconn.read_until(self.NORMAL_PROMPT) return
def QYT_TelnetClient(ip, username, password, enable, *cmds): 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(b'enable\n') time.sleep(1) rackreply = tn.expect([], timeout=1)[2].decode().strip() print(rackreply) tn.write(enable.encode()) tn.write(b'\n') rackreply = tn.expect([], timeout=1)[2].decode().strip() print(rackreply) time.sleep(1) for cmd in cmds: #读取命令,并且逐个执行! tn.write(cmd.encode() + b'\n') rackreply = tn.expect([], timeout=1)[2].decode().strip() print(rackreply) time.sleep(1) tn.write(b'exit\n') rackreply = tn.expect([], timeout=1)[2].decode().strip() print(rackreply) tn.close()
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:"******"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 machine\r\n") tn.write(b"machine.reset()\r\n") time.sleep(2) 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
def handler(self, **args): """gets kernel status""" print "kernelStatus" from telnetlib import Telnet import string connection=Telnet("kernel.org", 79) connection.write("\n") text="" text = connection.read_all() # Extract just the version numbers, instead of flooding # the channel with everything. result = "" for line in text.split("\n"): if len(line.split(":")) > 1: line = line.split(" ", 2)[2] version = string.strip(line.split(":")[1]) + " ;; " line = line.split("of", 2)[0] line = line.split("for", 2)[0] line = line.split("to", 2)[0] result += string.strip(line) + ": " + version from irclib import Event target = self.return_to_sender(args) return Event("privmsg", "", target, [ result ])