def ospf_telnet_open(): telnet_pointer=Telnet('127.0.0.1','2604') telnet_pointer.read_until("Password:"******"zebra\n") telnet_pointer.write("en\n") telnet_pointer.write("conf t\n") return telnet_pointer
def initConnection(host, port, timeout): """initiate connection to PNA and returns Telnet object tn if connection is succesfull returns object tn """ try: tn = Telnet(host, port, timeout) ans = tn.read_until("SCPI> ".encode(encoding='ascii', errors='strict'), timeout = 10).decode('ascii').strip() if debugCommunication: print(ans) else: pass tn.write("*IDN?".encode(encoding='ascii', errors='strict')) tn.write(termChar.encode(encoding='ascii', errors='strict')) # just send ENTER to execute the command ans = tn.read_until("SCPI> ".encode(encoding='ascii', errors='strict'), timeout = 5).decode('ascii').strip() if debugCommunication: print(ans) else: pass return tn except: print("Error while connecting.")
def update(self): tn = Telnet(self.host, self.port, self.timeout) tn.write(b'version\n') ret = tn.read_until(b'\r\n', self.timeout).decode('utf-8') logger.debug('version: %s', ret) version_list = ret.split(' ') if len(version_list) != 2 or version_list[0] != 'VERSION': raise ElasticacheInvalidTelentReplyError(ret) version = version_list[1][0:-2] if StrictVersion(version) >= StrictVersion('1.4.14'): get_cluster = b'config get cluster\n' else: get_cluster = b'get AmazonElastiCache:cluster\n' tn.write(get_cluster) ret = tn.read_until(b'END\r\n', self.timeout).decode('utf-8') logger.debug('config: %s', ret) tn.close() p = re.compile(r'\r?\n') conf = p.split(ret) if len(conf) != 6 or conf[4][0:3] != 'END': raise ElasticacheInvalidTelentReplyError(ret) version = int(conf[1]) servers = [] nodes_str = conf[2].split(' ') for node_str in nodes_str: node_list = node_str.split('|') if len(node_list) != 3: raise ElasticacheInvalidTelentReplyError(ret) servers.append(node_list[0] + ':' + node_list[2]) with self.lock: if version > self.version: self.servers = servers self.version = version self.timestamp = time.time() logger.debug('cluster update: %s', self)
def __init__(self, endpoint, timeout): host, port = endpoint.split(':') elasticache_logger.debug('cluster: %s %s %s %s %s %s', str(host), str(type(host)), str(port), str(type(port)), str(timeout), str(type(timeout))) tn = Telnet(host, port) tn.write('version\n') ret = tn.read_until('\r\n', timeout) elasticache_logger.debug('version: %s', ret) version_list = ret.split(' ') if len(version_list) != 2 or version_list[0] != 'VERSION': raise ElasticacheInvalidTelentReplyError(ret) version = version_list[1][0:-2] if StrictVersion(version) >= StrictVersion('1.4.14'): get_cluster = 'config get cluster\n' else: get_cluster = 'get AmazonElastiCache:cluster\n' tn.write(get_cluster) ret = tn.read_until('END\r\n', timeout) elasticache_logger.debug('config: %s', ret) tn.close() p = re.compile(r'\r?\n') conf = p.split(ret) if len(conf) != 6 or conf[4][0:3] != 'END': raise ElasticacheInvalidTelentReplyError(ret) self.version = conf[1] self.servers = [] nodes_str = conf[2].split(' ') for node_str in nodes_str: node_list = node_str.split('|') if len(node_list) != 3: raise ElasticacheInvalidTelentReplyError(ret) self.servers.append(node_list[1] + ':' + node_list[2])
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")
class TelnetConnect(object): def __init__(self,ip_addr,username,password): self.ip_addr=ip_addr self.username=username self.password=password try: self.remote_conn= Telnet(self.ip_addr, TELNET_PORT, TELNET_TIMEOUT) except soket.timeout: sys.exit("Timeout Connection") def login(self,sleep_time=1): output=self.remote_conn.read_until('sername:',TELNET_TIMEOUT) self.remote_conn.write(self.username +'\n') output+=self.remote_conn.read_until('assword:', TELNET_TIMEOUT) self.remote_conn.write(self.password+'\n') time.sleep(sleep_time) output+=self.remote_conn.read_very_eager() return output def send_command(self,cmd,sleep_time=1): cmd=cmd.rstrip() self.remote_conn.write(cmd + '\n') time.sleep(sleep_time) return self.remote_conn.read_very_eager() def close_conn(self): self.remote_conn.close()
class Player(Player): @classmethod def running(self): try: Telnet(lyvi.config['mpd_host'], lyvi.config['mpd_port']).close() return True except OSError: return False def __init__(self): """Get a path to the music directory and initialize the telnet connection.""" self.music_dir = None if os.path.exists(lyvi.config['mpd_config_file']): for line in open(lyvi.config['mpd_config_file']): if line.strip().startswith('music_directory'): self.music_dir = line.split('"')[1] self.telnet = Telnet(lyvi.config['mpd_host'], lyvi.config['mpd_port']) self.telnet.read_until(b'\n') def get_status(self): data = {'artist': None, 'album': None, 'title': None, 'file': None, 'length': None} self.telnet.write(b'status\n') response = self.telnet.read_until(b'OK').decode() self.telnet.write(b'currentsong\n') response += self.telnet.read_until(b'OK').decode() t = { 'state: ': 'state', 'Artist: ': 'artist', 'Title: ': 'title', 'Album: ': 'album', 'file: ': 'file', 'time: ': 'length', } for line in response.splitlines(): for k in t: if line.startswith(k): data[t[k]] = line.split(k, 1)[1] break data['file'] = os.path.join(self.music_dir, data['file']) if data['file'] and self.music_dir else None data['length'] = int(data['length'].split(':')[1]) if data['length'] else None for k in data: setattr(self, k, data[k]) def send_command(self, command): cmd = { 'play': b'play\n', 'pause': b'pause\n', 'next': b'next\n', 'prev': b'previous\n', 'stop': b'stop\n', }.get(command) if cmd: self.telnet.write(cmd) return True def cleanup(self): self.telnet.close()
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()
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 changeTorIP(self): tn = Telnet(self.serverIP, int(self.torControlPort)) tn.write("AUTHENTICATE\r\n") tn.read_until("250 OK", 2) tn.write("signal NEWNYM\r\n") tn.read_until("250 OK", 2) tn.write("QUIT\r\n") tn.close()
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 _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 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 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 retrieve(host, user='******', password=''): tn = Telnet(host) # user = bytes(user, 'utf8') # tn.set_debuglevel(255) tn.read_until(b'login: '******'%s\r\n' % user, 'utf8')) tn.read_until(b'Password: '******'%s\r\n' % password, 'utf8')) tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) tn.write(b'/usr/sbin/dsl_cpe_pipe.sh g997bansg 0\r\n') bits_up = tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) tn.write(b'/usr/sbin/dsl_cpe_pipe.sh g997bansg 1\r\n') bits_down = tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) #tn.write(b'/usr/sbin/dsl_cpe_pipe.sh g997gansg 0\r\n') #gain_up = tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) #tn.write(b'/usr/sbin/dsl_cpe_pipe.sh g997gansg 1\r\n') #gain_down = tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) tn.write(b'/usr/sbin/dsl_cpe_pipe.sh g997sansg 1\r\n') snr_down = tn.read_until(bytes('%s@gateway:~# ' % user, 'utf8')) tn.write(b'exit\r\n') bits_up = extract(normalise(bits_up)) bits_down = extract(normalise(bits_down)) bits = merge(bits_up, bits_down) snr_down = [x != 255 and x/2.55 or 0 for x in extract(normalise(snr_down))] #gain_up = extract(normalise(gain_up)) #gain_down = extract(normalise(gain_down)) #gain = merge(gain_up, gain_down) return bits, [], snr_down
def backup_FG50B(src, dest): cmd = 'execute backup full-config ftp FG50B 10.66.4.56 administrator !tsinim9' t = Telnet('10.66.7.252') sys.stdout.write( t.read_until('login:'******'admin\n') sys.stdout.write( t.read_until('Password:'******'!tsinim9\n') sys.stdout.write( t.read_until('#')) t.write('%s\n' % cmd) sys.stdout.write( t.read_until('OK.')) t.close()
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()
def cmd_wake_slave(ensoapi): """Wake a slave server with a magic packet""" tn = Telnet(HOST) tn.read_until("login: "******"\n") tn.read_until("Password: "******"\n") tn.write("/usr/sbin/wol -i 192.168.1.255 -p 9 00:00:00:00:00:00\n") # provide a MAC address tn.write("exit\n") tn.read_all()
def cmd_wan_reconnect(ensoapi): """Reconnect WAN""" tn = Telnet(HOST) tn.read_until("login: "******"\n") tn.read_until("Password: "******"\n") tn.write("killall -HUP pppd\n") tn.write("exit\n") tn.read_all()
def backup_FG100A(src, dest): #cmd = 'execute backup allconfig FG100A 192.168.1.101' cmd = 'execute backup full-config tftp FG100A %s' % dest t = Telnet(src) sys.stdout.write(t.read_until('login:'******'admin\n') sys.stdout.write( t.read_until('Password:'******'!tsinim9\n') sys.stdout.write( t.read_until('#')) t.write('%s\n' % cmd) sys.stdout.write( t.read_until('OK.'))
def _do_probe(ip_address, port, user, password): try: client = Telnet(ip_address, port, DEFAULT_TIMEOUT) client.read_until('login: '******'\n') client.read_until('Password: '******'\n') client.write('exit\n') client.close() return True except: return False
def getIpInterfaces(host,user,password): timeout = 6 port = 23 remote_conn = Telnet(host,port,timeout) remote_conn.read_until(b"sername:") remote_conn.write(username.encode('ascii') + b"\n") remote_conn.read_until(b"assword:") remote_conn.write(password.encode('ascii') + b"\n") remote_conn.write(b"show ip int brief" + b"\n") time.sleep(2) output = remote_conn.read_very_eager() remote_conn.close() print(output.decode() + "\n")
class TelnetServerControl(AgentControl): """ Inherit from AgentControl. Implement all existing methods in the way of Telnet. It's meant to interact with a linux server instead of a network device. """ def __init__(self): super(TelnetServerControl, self).__init__() self.tn = None def login(self, identity): self.tn = Telnet(identity.ip) print self.tn.read_until("login: "******"\n") print self.tn.read_until("Password: "******"\n") feedback = self.tn.read_until('$', 5) return def exec_cmd(self, command): self.tn.write(command + "\n") feedback = self.tn.read_until('$', 5) print "feedback:", feedback return feedback def logout(self): self.tn.write('exit\n') print self.tn.read_until('$', 5) return
def main(hostname, username, password): t = Telnet(hostname) # t.set_debuglevel(1) # uncomment to get debug messages t.set_option_negotiation_callback(process_option) t.read_until(b'login:'******'utf-8') + b'\r') t.read_until(b'assword:', 10) # first letter might be 'p' or 'P' t.write(password.encode('utf-8') + b'\r') n, match, previous_text = t.expect([br'Login incorrect', br'\$'], 10) if n == 0: print("Username and password failed - giving up") else: t.write(b'exec echo My terminal type is $TERM\n') print(t.read_all().decode('ascii'))
def telnet_handler(host, dump, passw, set_name): if not host: host = '127.0.0.1' port = 23 tftphost = '200.2.127.150' tftppath = '' # e.g: tftppath = 'mdump/' # connect print "Connecting to %s..." % host tn = Telnet(host, port) #tn.set_debuglevel(5) #print "waiting for login string..." tn.read_until("login: "******"\n") #print "waiting for password string..." tn.read_until("password: "******"\n") tn.read_until(set_name + "> ") cmd = "dump network %s %s" % (tftphost, tftppath + dump) print "running \"%s\" on host %s" % (cmd, host) tn.write(cmd + '\n') tn.read_until(set_name + "> ") tn.write('logout\n') print "Logging out from %s..." % host print tn.read_all() print "Bye."
def executeBackdoor(self): try: tn = Telnet('192.168.1.1') print '[+] connection established' tn.read_until('#', self.timeout) #make self.tcmd('chmod +x /data/video/backdoor.sh', tn) self.tcmd('/data/video/backdoor.sh', tn) except Exception as e: print '[ERROR] telnet command execution failed' print e.message finally: return 0
def _run_command(self, cmd: str, ok="OK") -> bool: """ sends a telnet command to the host :param cmd: :return: bool successful """ telnet = Telnet(self.ip, self.telnet_port, 60) try: response = telnet.read_until(b'>', timeout=0.1) self.logger.debug("Intial response is: {0!s}".format(response.decode())) # we MUST wait a little bit before writing to ensure that the stream isnt being written to. time.sleep(0.5) # encode to ascii and add LF. unfortunately this is not to the telnet spec (it specifies CR LF or LF CR I'm ns) telnet.write(cmd.encode("ascii") + b"\n") ok_regex = re.compile(b'.*'+ok.encode("ascii")+b'.*') response = telnet.expect([ok_regex], timeout=30) if response[0] < 0: return False else: return True except: self.logger.error(traceback.format_exc()) return False finally: telnet.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 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
def do_telnet(host, username, password, finish, commands): tn = Telnet(host, port=23, timeout=10) tn.set_debuglevel(2) if username: expect2(tn, [r'login: '******'utf8') + b"\n")) if password: expect2(tn, [r'Password: '******'utf8') + b"\n")) tn.read_until(finish) for command in commands: tn.write(b'%s\n' % command.encode('utf8')) tn.read_until(finish) tn.close() # tn.write('exit\n')
class TelnetDriver(Driver): """Represents a connection with Telnet""" def __init__(self, target, username='', password='', port=23, username_finder='username: '******'password: '******'' or self.password != '': self.expect(self.username_finder) self.send_text(self.username) self.expect(self.password_finder) self.send_text(self.password) def send_text(self, text): try: self._client.write(text.encode('ascii')) return True except socket.error: raise DriverError("Connection closed while sending text") def read_until(self, text, timeout=2): try: return self._client.read_until(text.encode('ascii'), timeout) except EOFError: raise DriverError("Connection closed without receiving EOF") def read_eof(self, timeout=2): return self._client.read_all() def expect(self, expr_list, timeout=2): try: return self._client.expect(expr_list, timeout) except EOFError: raise DriverError( "EOF was reached without finding the expected text") def close(self): self._client.close()
def abort(): telnet = Telnet("pico25.niddk.nih.gov") telnet.read_until("login: "******"root\n") telnet.read_until("Password: "******"root\n") telnet.read_until("# ") telnet.write("killall cat\n") telnet.read_until("# ") telnet.close()
def telnet(ip_address, command): """Execute a shell command remotely""" from telnetlib import Telnet # For performance reasons, keep the connection open across repeated calls. # Also allow connections to multiple servers be open at the same time. if not ip_address in telnet_connections: telnet_connections[ip_address] = None connection = telnet_connections[ip_address] while True: if connection is None: try: connection = Telnet(ip_address) connection.read_until("login: "******"root\n") connection.read_until("Password: "******"root\n") connection.read_until("# ") except Exception, msg: error("Telnet %r: %s" % (ip_address, msg)) connection = None reply = "" break try: connection.write(command + "\n") reply = connection.read_until("# ") break except Exception, msg: warn("telnet %r,%r: %s" % (ip_address, command, msg)) connection = None continue
class TelnetClient(object): 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:'******'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('$ ') 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 __enter__(self): self.tn = Telnet(self.addr,self.port) self.history = deque() return self def __exit__(self,exc_type,exc_val,exc_tb): self.tn.close() self.tn = None with open(self.addr + '_history.txt','w') as f: f.writelines(self.history)
def set_vision_sensor_online_state(value): tValue = str(value) try: tn = Telnet(tn_HOST, 23, tn_timeout) # Login to Sensor # print("Telnet connected") tn.read_until(b"User: "******"\r\n") tn.read_until((b"Password: "******"\r\n") tn.read_until(b"User Logged In\r\n") # Login Finished tn.write(b"SO" + tValue.encode('ascii') + b"\r\n") # print("set sensor_state to: " + tValue) call_ok = str(tn.read_until(b"\r\n"), 'utf-8') call_ok = call_ok.replace("\r\n", "") # print("callOK: " + call_ok) if call_ok == "1": if value == 0: App.get_running_app().vs_is_online = False if value == 1: App.get_running_app().vs_is_online = True return call_ok tn.close() except IOError: print("error while connecting to vision-sensor") return -5, None
def run(self): _LOGGER.debug(f"{self.gw.host} | Start BLE ") while True: try: telnet = Telnet(self.gw.host, timeout=5) telnet.read_until(b"login: "******"admin\r\n") telnet.read_until(b"\r\n# ") # skip greeting telnet.write(b"killall silabs_ncp_bt; " b"silabs_ncp_bt /dev/ttyS1 1\r\n") telnet.read_until(b"\r\n") # skip command while True: raw = telnet.read_until(b"\r\n") if 'bluetooth' in self.gw.debug: _LOGGER.debug(f"[BT] {raw}") if b'_async.ble_event' in raw: self.gw.process_ble_event(raw) except (ConnectionRefusedError, ConnectionResetError, EOFError, socket.timeout): pass except Exception as e: _LOGGER.exception(f"Bluetooth loop error: {e}") time.sleep(30)
def cmd_wake(ensoapi, machine): """Wake a workstation with a magic packet sent to a given MAC-address Requires the following variables in Enso custom initialization block:<br> DD_WRT_HOST = "dd-wrt router ip" #default: "192.168.1.1"<br> DD_WRT_USER = "******" #default: "root"<br> DD_WRT_PASSWORD = "******"<br> DD_WRT_MACHINES = {'shell': "AA:BB:CC:DD:EE:FF"} """ tn = Telnet(HOST, 23) tn.read_until(b"login: "******"\n") tn.read_until(b"Password: "******"\n") tn.write(b"/usr/sbin/wol -i 192.168.1.255 -p 9 " + MACHINES[machine].encode('ascii', 'ignore') + b"\n") tn.write(b"exit\n") tn.read_all()
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반환
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 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
class TelnetDevice(object): ''' Class details here ''' def __init__(self, *args, **kwargs): self.ip_addr = kwargs.get('ip_addr') self.username = kwargs.get('username') self.password = kwargs.get('password') self.telnet_port = kwargs.get('telnet_port', 23) self.telnet_timeout = kwargs.get('telnet_timeout', 8) self.dev = { 'ip': self.ip_addr, 'username': self.username, 'password': self.password, 'telnet_port': self.telnet_port, 'telnet_timeout': self.telnet_timeout } self._connect(self.dev) def _connect(self, *args, **kwargs): try: self.remote_conn = Telnet( self.ip_addr, self.telnet_port, self.telnet_timeout) self.output = self.remote_conn.read_until( 'sername:', self.telnet_timeout) self.remote_conn.write(self.username + '\n') self.output += self.remote_conn.read_until( 'ssword:', self.telnet_timeout) self.remote_conn.write(self.password + '\n') return self.remote_conn except socket.timeout: sys.exit('Connection timeout') def send_command(self, cmd, **kwargs): cmd = cmd.rstrip() self.remote_conn.write(cmd + '\n') time.sleep(1) return self.remote_conn.read_very_eager() def _close(self, *args, **kwargs): self.remote_conn.close()
class TelnetRemoteConn(object): def __init__(self, ip, port, timeout): self.ip_addr = ip self.port = port self.timeout = timeout self.telnet_session = None self.log = "" self.prompt = "" def open_session(self): try: self.telnet_session = Telnet(self.ip_addr, self.port, self.timeout) self.log += "Session to %s:%s opened" % (self.ip_addr, self.port) except socket.timeout: self.log += "Failed to open connection to %s" % self.ip_addr def login(self, username, password): prompts = [">", "$", "#"] if (self.telnet_session): self.log += self.telnet_session.read_until("sername", self.timeout) self.telnet_session.write(username + '\n') self.log += self.telnet_session.read_until("ssword", self.timeout) self.telnet_session.write(password + '\n') self.prompt = self.telnet_session.expect(prompts, self.timeout)[2] self.log += self.prompt else: self.log += "Unable to Login: No Connection" def logout(self): self.telnet_session.write("exit" + '\n') self.telnet_session.close() def send_command(self, command): if (self.telnet_session): self.telnet_session.write(command + '\n') time.sleep(1) output = self.telnet_session.read_very_eager() self.log += output output_list = output.split('\n') output_list = output_list[1:-1] output = '\n'.join(output_list) return output else: self.log += "Unable to send command: No connection"
class Session: def __init__(self, host, port, username, password): # Устанавливаем соединение self.telnet = Telnet(host, port, 5) # Ожидаем указанную строку в течении 5 секунд self.read_until("Login id:") # Вводим имя пользователя self.write(username + "\n") # Ожидаем указанную строку в течении 5 секунд self.read_until("Password:"******"\n") # Ожидаем указанную строку в течении 5 секунд 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_users_registred(self, username): # Вводим команду на проверку существования пользователя self.write("verify %s\n" % username) # Задаем список возможных ответов при проверке попльзователя (b - преобразует строку в байты) res = self.telnet.expect([b"exists", b"does not exist"]) # Если получаем значение из списка с индексом 0 тогда пользователь существует return res[0] == 0 def create_user(self, username, password): # Вводим команду на добавление нового пользователя self.write("adduser %s %s\n" % (username, password)) # Ожидаем указанную строку в течении 5 секунд self.read_until("User % added" % username) def reset_password(self, username, password): # Вводим команду на изменение пароля пользователя self.write("setpassword %s %s\n" % (username, password)) # Ожидаем указанную строку в течении 5 секунд self.read_until("Password for % reset" % username) def quit(self): self.write("quit\n")
def get_gateway_info(self): 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}): ([A-F0-9]{16}) 0 JOINED (\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} md = ('nwk|eid64|ago|type|parent|name\n' '---|-----|---|----|------|----') for i in m1: nid = i[0] eid64 = i[1] last_seen = i[2] if eid64 in m2: type_ = 'device' elif eid64 in m3: type_ = 'router' else: type_ = '-' parent = m4[nid][0] if nid in m4 else '-' did = 'lumi.' + re.sub(r'^0*', '', eid64).lower() device = self.devices.get(did) name = device['device_name'] if device else '-' try: md += '\n' + '|'.join( [nid, eid64, last_seen, type_, parent, name]) except: print() return md
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()
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")
class e7_telnet(object): def __init__(self): print "self:", self() pass def telnet_e7(self, host, port, type=None): self.Tel = Telnet(host, port) # self.Tel.debuglevel(0) res = self.Tel.read_until(": " or "# " or "~ ") return self.Tel
class ReceiveSignal: def __init__(self): self.tn = Telnet('localhost', 13854) self.tn.write( '{"enableRawOutput": true, "format": "Json"}'.encode('ascii')) self.f = open('output', 'a') def checkDataSource(self): """ {u'eegPower': {u'lowGamma': 5144, u'highGamma': 2510, u'highAlpha': 18055, u'delta': 53387, u'highBeta': 13139, u'lowAlpha': 27772, u'lowBeta': 6340, u'theta': 81641}, u'poorSignalLevel': 0, u'eSense': {u'meditation': 61, u'attention': 50}} """ eegData = {'blinkstrength': 0, 'attention': 0} while True: line = self.tn.read_until(b'\r') jsonValue = json.loads(line.decode('utf-8')) output = [] if "rawEeg" not in jsonValue: # print(str(jsonValue)) pass if 'eegPower' in jsonValue: eegData['lowGamma'] = int(jsonValue['eegPower']['lowGamma']) eegData['highGamma'] = int(jsonValue['eegPower']['highGamma']) eegData['highAlpha'] = int(jsonValue['eegPower']['highAlpha']) eegData['delta'] = int(jsonValue['eegPower']['delta']) eegData['highBeta'] = int(jsonValue['eegPower']['highBeta']) eegData['lowAlpha'] = int(jsonValue['eegPower']['lowAlpha']) eegData['lowBeta'] = int(jsonValue['eegPower']['lowBeta']) eegData['theta'] = int(jsonValue['eegPower']['theta']) output.append(eegData['lowGamma']) output.append(eegData['highGamma']) output.append(eegData['highAlpha']) output.append(eegData['delta']) output.append(eegData['highBeta']) output.append(eegData['lowAlpha']) output.append(eegData['lowBeta']) output.append(eegData['theta']) # print(eegData['lowGamma'], eegData['lowGamma'], eegData['highAlpha'], eegData['delta']) if "eSense" in jsonValue: eegData['attention'] = int(jsonValue['eSense']['attention']) eegData['meditation'] = int(jsonValue['eSense']['meditation']) # print('attention:\t' + str(eegData['attention'])) output.append(eegData['attention']) output.append(eegData['meditation']) if "blinkStrength" in jsonValue: eegData['blinkstrength'] = int(jsonValue['blinkStrength']) print('blinkstrength:\t' + str(eegData['blinkstrength'])) # output.append(eegData['blinkstrength']) if len(output) >= 10: print(output) writeToFile(output)
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}
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
def do_ws_srv_telnet(source: str) -> None: HOST = "localhost" print("telnet {} {} SEL {}".format(HOST, config.get("shittyserver", "telnet_port"), source)) tn = Telnet(HOST, int(config.get("shittyserver", "telnet_port"))) tn.write(b"SEL " + str.encode(source) + b"\n") try: print(tn.read_until(b"\n").decode("utf-8")) except EOFError: pass else: tn.close()
def main(): t = Telnet("localhost", 2333) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") while True: if (result := t.read_until(b"\n")): try: z, a, b = result.decode("utf-8").split("\t") except ValueError: continue soa = np.array([[0, 0, 0] + list(map(float, a.split(" ")))]) ax.set_xlim([-1, 1]) ax.set_ylim([-1, 1]) ax.set_zlim([-1, 1]) ax.quiver(*zip(*soa)) plt.draw() plt.pause(0.001) ax.clear()
class telnet(): def __init__(self, ip, port, username, password): self.ip = ip self.port = port self.username = username self.password = password def connect(self, *username): self.session = Telnet(self.ip, self.port) for x in username: self.username = username[0] if b'Username:'******'Username:'******'ascii') + b"\r\n") if b'Password:'******'Password:'******'ascii') + b"\r\n") else: raise ConnectionError('Failed to establish telnet connection.')
def main(): tn = Telnet() tn.open('10.100.218.8', 23, 3) ret = tn.read_until('username:'******'admin' + '\n') ret = tn.read_until('password:'******'admin' + '\n') ret = tn.read_until('>') print ret tn.write('show vlan') time.sleep(2) ret = tn.read_very_eager() print ret tn.close()
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 retries = 0 while True: 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=10) print("Connected via telnet again, lets check the git tag") break except socket.timeout: if retries < 5: print("Timeout while connecting via telnet, retrying...") retries += 1 else: print('Error: Telnet connection timed out!') return False try: 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
def _enable_mqtt(self): _LOGGER.debug(f"{self.host} | Try run public MQTT") try: telnet = Telnet(self.host) telnet.read_until(b"login: "******"admin\r\n") telnet.read_very_eager() # skip response # enable public mqtt telnet.write(b"killall mosquitto\r\n") telnet.read_very_eager() # skip response time.sleep(.5) telnet.write(b"mosquitto -d\r\n") telnet.read_very_eager() # skip response time.sleep(1) telnet.close() return True except Exception as e: _LOGGER.debug(f"Can't run MQTT: {e}") return False
def router_telnet_process(self, node, name, console_host, console): os.chdir(FILE_DIRECTION+'/projects/'+self.topology) self.start_gns3(node, name) #print("Configuring %s ..."%(name)) config_file = open("R%d.cfg"%(int(name.split("-")[-1])), "r") command = config_file.read().split('\n') telnet_connect=Telnet(console_host, str(console)) telnet_connect.read_until(b"Would you like to enter the initial configuration dialog? [yes/no]:", timeout=5*60) telnet_connect.write("no".encode('ascii') + b"\r\n") telnet_connect.write(b"\r\n") #telnet_connect.set_debuglevel(2) time.sleep(60) telnet_connect.write(b"\r\n") telnet_connect.read_until(b"Router>") telnet_connect.write("enable".encode('ascii')+b"\r\n") telnet_connect.write("configure terminal".encode('ascii')+b"\r\n") for c in command: telnet_connect.write(c.encode('ascii')+b"\r\n") time.sleep(0.2) telnet_connect.close() sys.stdout.flush()
def telnet_connect(msg): HOST = '100.98.10.148' PORT = 1025 tn = Telnet(HOST, PORT) line = tn.read_until("An apple a day keeps the doctor away\r\n") print(line) tn.write(b'GOOD\r\n') line = tn.read_until("\n") print(line) tx = '' for key, value in msg.items(): tx += key + ': ' + str(value) + '\r\n' print("Sending data: {}".format(tx)) tn.write(b'{}'.format(tx)) line = tn.read_until("\n") print("Closing the connection ...") tn.close()
class Mozrepl(object): def __init__(self, ip="127.0.0.1", port=4242): self.ip = ip self.port = port self.prompt = b"repl>" def __enter__(self): self.t = Telnet(self.ip, self.port) intro = self.t.read_until(self.prompt, 1) if not intro.endswith(self.prompt): self.prompt = re.search(br"repl\d+>", intro).group(0) print("Waited due to nonstandard prompt:", self.prompt.decode()) return self def __exit__(self, type, value, traceback): self.t.close() del self.t def js(self, command): self.t.write(command.encode() + b"\n") return self.t.read_until(self.prompt)[2:-7].decode()
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: "******"\n") #the note above also applies for this telnet.read_until("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)