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 send_telnet_command(self, cmd): from telnetlib import Telnet self.logger.debug("Starting a Telnet session...") t = Telnet(self.config.option("IP").value) self.logger.debug("[SRV] " + t.read_until(b"login: "******"utf-8")) self.logger.debug("[CLT] " + "root") t.write(b"root\n") self.logger.debug("[SRV] " + t.read_until(b"assword: ").decode("utf-8")) pswd = self.config.option("PASSWORD").value self.logger.debug("[CLT] " + pswd) t.write(pswd.encode("utf-8") + b"\n") resp = t.read_until(b"~ # ") self.logger.debug("[SRV] " + resp.decode("utf-8")) success = False if b"Welcome to HiLinux." in resp: self.logger.debug("[CLT] " + cmd) t.write(cmd.encode("utf-8") + b"\n") self.logger.success("Telnet command sent") success = True self.logger.debug("[CLT] exit") t.write(b"exit\n") t.read_all() else: self.logger.failure("Bad Telnet password") t.close() return success
def multithread_test(): req = [ "GET /echo HTTP/1.1", "Host: localhost:3000", "Connection: keep-alive", "Upgrade-Insecure-Requests: 1" ] req += ["User-Agent: telnet", "Accept: */*"] req = "\r\n".join(req) req += "\r\n\r\n" print "Starting connection1 with half request" connection1 = Telnet('localhost', 3000) connection1.write(req.split('Accept')[0]) print "Starting connection2 with full request" connection2 = Telnet('localhost', 3000) connection2.write(req) res2 = connection2.read_all() print "Completing the request of connection1" connection1.write("Accept: */*\r\n\r\n") res1 = connection1.read_all() if res1 != res2: print "Same requests are giving different responses" exit(4) else: print "Multi threading tests passed." print "The two connections give the same response."
def _show_run(self,get_switch,get_switch_property,get_switch_access): ### variable arrange switch_name = get_switch['name'] network_inform = get_switch['ip'] telnet_port = network_inform.split(':')[1] telnet_ip = network_inform.split(':')[0].split('/')[0] telnet_user = get_switch_access['account'] telnet_pass = get_switch_access['password'] telnet_enable = get_switch_access['enable'] ### telnet open time out in second self.telnet_open_timeout = float(10) ### telnet open processing try: telnet_pointer = Telnet(telnet_ip,telnet_port,self.telnet_open_timeout) except: msg="[ error : "+time.asctime()+" ] can't open the telnet, ip : "+telnet_ip+", port :"+telnet_port self.logging_msg(self.run_syslog,msg) sys.exit() ### telnet login processing try: line_result = telnet_pointer.expect(Arista_manage._login_pattern,self.telnet_open_timeout)[1] except: msg="[ error : "+time.asctime()+" ] can't 2read login pattern : "+str(Arista_manage._login_pattern) self.logging_msg(self.run_syslog,msg) sys.exit() if not line_result: sys.exit() ### insert account for login telnet_pointer.write(telnet_user+"\n") ### wait the password pattern try: telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout) except: msg="[ error : "+time.asctime()+" ] can't read login pattern : "+str(Arista_manage._passwd_pattern) self.logging_msg(self.run_syslog,msg) sys.exit() telnet_pointer.write(telnet_pass+"\n") print telnet_pointer.expect([switch_name+"\w*>"],self.telnet_open_timeout) telnet_pointer.write("enable1234\n") print telnet_pointer.expect(Arista_manage._passwd_pattern,self.telnet_open_timeout) telnet_pointer.write(telnet_enable+"\n") print telnet_pointer.expect([switch_name+"\w*#"],self.telnet_open_timeout) telnet_pointer.write("exit\n") telnet_pointer.read_all() telnet_pointer.close()
class TelnetPhapiServer: from telnetlib import Telnet def __init__(self, target, cmd="phapiserver", killold=True): self.tn = Telnet(target); if killoold: self.tn.write("killall phapiserver\r\nexit\r\n") def terminate(self): self.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()
class TelnetPhapiServer: from telnetlib import Telnet def __init__(self, target, cmd="phapiserver", killold=True): self.tn = Telnet(target) if killoold: self.tn.write("killall phapiserver\r\nexit\r\n") def terminate(self): self.tn.read_all()
def cmd_wan_reconnect(ensoapi): """Reconnect WAN""" tn = Telnet(HOST, 23) tn.read_until(b"login: "******"\n") tn.read_until(b"Password: "******"\n") tn.write(b"killall -HUP pppd\n") tn.write(b"exit\n") tn.read_all()
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()
async def test_send_message(mailbox): mail_count = len(mailbox) tn = Telnet('localhost', port=8025) tn.write(b'EHLO test.nutty.dev\r\n') tn.write(b'MAIL FROM: [email protected]\r\n') tn.write(b'RCPT TO: [email protected]\r\n') tn.write(b'DATA\r\n') tn.write(b'Subject: Test Email\r\n\r\n') tn.write(b'Hello, this is a test email from test_send_message\r\n\r\n') tn.write(b'.\r\n') tn.write(b'QUIT\r\n') tn.read_all() assert len(mailbox) > mail_count
def Switch(ip,user,password): try: tn = Telnet() tn.open(host=ip, port=23) response = 'Success' tn.write(user.encode('utf-8') + b"\n") if password: tn.read_until(b"Password: "******"\n") except: response = 'Failed' finally: print (response) tn.write(b"Terminal len 0\n") tn.write(b"sh inventory\n") tn.write(b"sh env all\n") tn.write(b"sh version\n") tn.write(b"sh clock\n") tn.write(b"show vlan\n") tn.write(b"sh process cpu\n") tn.write(b"sh process memory\n") tn.write(b"sh logging\n") tn.write(b"ls\n") tn.write(b"exit\n") readoutput = tn.read_all().decode('utf-8') f = open ("Output.txt" , "w") f.write (readoutput) f.close
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 mirrors(): """Get the mirror numbers""" HOST = 'sdss4-host2.apo.nmsu.edu' PORT = 2001 # Open the network connection try: tn = Telnet(HOST, PORT) except Exception: print('Telnet connection to %s:%d failed: %s' % (HOST, PORT, format_exc())) return -1 # Read the data try: tn.write('\n') except Exception: print('Telnet write to %s:%d failed: %s' % (HOST, PORT, format_exc())) return -1 try: reply = tn.read_all() except Exception: print('Telnet read from %s:%d failed: %s' % (HOST, PORT, format_exc())) return -1 tn.close() return reply
def get_xml_data(hostname, timeout, node_failures, node_failure_threshold): xml_data = None try: t = Telnet() t.open(hostname, 8649, timeout) except socket.timeout: # currently only incrementing failure count for nodes that time out. # the other failures happen quickly enough to have little to no impact # on total elapsed time, and thus aren't worthy worrying about ERR ("timeout connecting to host {0}. recording failure".format(hostname)) node_failures[hostname] += 1 WARN ("host {0} has failed {1} times - {2} more failures before removal from host list".format(hostname, node_failures[hostname], node_failure_threshold - node_failures[hostname])) return "node_failed" except socket.gaierror: ERR ("host not found: {0}".format(hostname)) except socket.error: ERR ("could not connect to host - connection refused: {0}".format(hostname)) else: D (1, "successfully connected to host {0}".format(hostname)) try: xml_data = t.read_all() except: ERR ("couldn't read data from host {0}".format(hostname)) else: D (3, "XML dump:\n{0}".format(xml_data)) t.close() D (1, "connection to {0} closed".format(hostname)) return xml_data
def snr_clear_errors_on_port(incoming_value, host): """ Посылает на коммутатор SNR команды для сброса количества ошибок на порту. :param dict incoming_value: словарь с входящими данными :param str host: ip-адрес устройства для которого выполняется запрос :rtype: dict :return: словать с результатом выполнения сброса """ # получаем индекс порта и количество CRC ошибок port_index, input_crc_count = incoming_value['CRC'].popitem() try: conn = Telnet(host, port=23, timeout=3) conn.read_until(b'login:'******'ascii') + b'\n') conn.write(telnet_password.encode('ascii') + b'\n') # шлем команду на сброс счетчиков clear_command = 'clear counters interface ethernet 1/0/{}'.format( port_index) conn.write(clear_command.encode('ascii') + b'\n') # разлогиниваемся conn.write(b'exit\n') logging.debug(conn.read_all()) except Exception as err: logging.exception(err) return {'clear_errors': {str(port_index): 'Failed'}} else: return {'clear_errors': {str(port_index): 'Success'}}
def checkvalves(self): tell = Telnet("192.168.1.23",1234) tell.write('remote\r') output = tell.read_all() print(output) return
def connect(self): tn = Telnet("localhost") out = tn.read_until("login:"******"root\n") check = tn.read_until("Password:"******"Password:"******"\n") check = tn.read_until("~#", 2) out += check if check.__contains__("~#"): tn.write("passwd\n") out += tn.read_until("password", 2) tn.write(self.newp + "\n") out += tn.read_until("password", 2) tn.write(self.newp + "\n") out += tn.read_until("xxx", 1) tn.write("exit\n") out += tn.read_all() else: out += "\nLogin incorrect, wrong password." tn.close() self.connected = False self["lab"].setText(out)
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 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
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 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 _zk_tn(host_tpl, data): try: tn = Telnet(host=host_tpl[0], port=host_tpl[1], timeout=ZK_TIMEOUT) tn.write(data) ret = tn.read_all() tn.close() return ret except socket.error: return None
def cmd_wake(ensoapi, machine): """Wake a workstation with a magic packet sent to a given MAC-address Requires the following variables at the 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 = {'server': "AA:BB:CC:DD:EE:FF", 'gateway': "AA:BB:CC:DD:EE:FE"} """ 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 record_start(): """Telnet to the decks and start recording""" status = "" for deckname, ipaddress in hyperdecks.items(): tn = Telnet(ipaddress, TCP_PORT) tn.write(b'record' + b'\r\n') tn.write(b'quit' + b'\r\n') status += tn.read_all().decode('ascii') print(status)
def remote_enable(): status = "" for deckname, ipaddress in hyperdecks.items(): tn = Telnet(ipaddress, TCP_PORT) tn.write(b'remote: enable: true' + b'\r\n') tn.write(b'configuration: video input: SDI' + b'\r\n') tn.write(b'quit' + b'\r\n') status += tn.read_all().decode('ascii') print(status)
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 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 status(self): status = initdv2.ParametrizedInitScript.status(self) if not status and self.socks: ip, port = self.socks[0].conn_address telnet = Telnet(ip, port) telnet.write('HEAD / HTTP/1.0\n\n') if 'server: nginx' in telnet.read_all().lower(): return initdv2.Status.RUNNING return initdv2.Status.UNKNOWN return status
def record_stop(): """Telnet to the decks and stop recording""" status = "" for deckname, ipaddress in hyperdecks.items(): tn = Telnet(ipaddress, TCP_PORT) tn.write(b'stop' + b'\r\n') tn.write(b'quit' + b'\r\n') status += tn.read_all().decode('ascii') print(status) """Enables remote and sets the input"""
def convert(self): """Do the conversion from source to destination format. Returns boolean value telling if conversion was successful. """ ret = False if self.error_text: return ret # write source data to tmp-file sourceFile = mktemp('SVGrafZ') sfh = open(sourceFile, 'w') sfh.write(self.source) sfh.close() # create result file resultFile = mktemp('SVGrafZ') rfh = open(resultFile, 'w') rfh.write('ResultFile of SVGrafZ.') rfh.close() # try connection to batikServer try: conn = Telnet(config.SVGrafZ_BatikServer_Host, config.SVGrafZ_BatikServer_Port) cmd = 'CONF %s TO %s AS %s BSP 1.0\n\n' % (quote( sourceFile), quote(resultFile), self.getDestinationFormat()) conn.write(cmd) if conn.read_all(): ret = True conn.close() except Exception: # no batikServer, use batikRenderer cmd = config.SVGrafZ_Java_Path + \ ' -Djava.awt.headless=true -jar ' + \ config.SVGrafZ_Batik_Path + \ ' -d ' + resultFile + \ ' -m ' + self.getDestinationFormat() + \ ' ' + sourceFile pfh = os.popen(cmd) res = pfh.read() if res[-8:-1] == 'success': ret = True # read result if ret: rfh = open(resultFile, 'rb') self.result = rfh.read() rfh.close() # cleaning up if self.stylesheetPath: # XXX this can fail badly on windows unlink_queue.put((self.stylesheetPath, 0)) unlink_queue.put((sourceFile, 0)) unlink_queue.put((resultFile, 0)) return ret
def _exec_command(self): tn = Telnet(self._server, self._port, timeout=30) # tn.read_until('login: '******'\n') # tn.read_until('password: '******'\n') # tn.read_until(finish) tn.write('%s\n' % self._zkCommand) # tn.write('conf\n') tn.write('quit\n') self._value_raw = tn.read_all()
class TelnetClient: DEFAULT_PORT = 23 def __init__(self, host, port=DEFAULT_PORT): self.host = host self.port = port self.user = None self.password = None self.telnetInstance = None def areCredentialsSet(self): return self.user and self.password def setCredentials(self, user, password): self.user = user self.password = password def requestCredentials(self): self.user = input('Ingrese usuario de [%s]: ' % self.host) self.password = getpass() def connect(self): #Si aún no se han establecido solicitamos las credenciales (nombre de usuario y contraseña) if not self.areCredentialsSet(): self.requestCredentials() #Creamos una instancia de Telnet self.telnetInstance = Telnet(self.host) #Leemos todo el flujo de bytes hasta encontrar el mensaje Username: (solicitando que se ingrese) self.readUntil('Username: '******'ascii') + b"\n") if self.password: self.readUntil('Password: '******'ascii') + b'\n') self.executeCommand(self.password) return True return False def executeCommand(self, command): commandWithLineBreak = '%s\n' % command self.telnetInstance.write(bytes(commandWithLineBreak, 'ascii')) def readUntil(self, target): self.telnetInstance.read_until(target.encode('ascii')) def write(self, message): self.telnetInstance.write(bytes(message, 'ascii')) def interact(self): self.telnetInstance.interact() def printSession(self): print(self.telnetInstance.read_all().decode('ascii'))
def telnetexe(self,ip,user,passwd,cmd): tn = Telnet (ip) tn.read_until ("login: "******"\n") tn.read_until ("Password: "******"\n") tn.write (cmd + "\n") tn.write ("exit\n") TEMP = tn.read_all().decode("gbk") return TEMP
def _telnet(ip, port, input): tn = Telnet(ip, port) tn.write(input + '\n') output = '' try: output = tn.read_all() except: print 'error in reading telnet response...' tn.close() raise tn.close() return output
def get_data(self): self.hds = [] try: tn = Telnet(self.host, self.port) data = tn.read_all() data = unicode(data, errors='ignore') data = data.replace('\x10', '') tn.close() data = data.split('||') for i in data: self.hds.append(i.lstrip('|').rstrip('|').split('|')) except: self.hds = None
def respaldo_telnet(hostname, ip, cisco_os, username, password, enable_password): try: ruta = os.getcwd() with open( ruta + "/full backup manual/respaldo_" + hostname + "_" + datetime.now().strftime("%d%m%Y_%H%M"), "w") as file: if cisco_os == "nxos": print("....se conecta via telnet.." + hostname) tn = Telnet(ip) tn.read_all() tn.write(username.encode('utf-8')) tn.write(b"\r") tn.read_all() tn.write(password.encode('utf-8')) tn.write(b"\r") for comando in commands_nxos: print("...." + comando + "......") resultado = tn.write(comando + "\n") file.write(tn.read_all()) print(tn.read_all()) elif cisco_os == "iosxe": print("....se conecta via telnet.." + hostname) tn = Telnet(ip) tn.read_until(b"Username: "******"alex") tn.read_until(b"Password: "******"alex") tn.read_until(b"#") except Exception as e: print(e) return (e) return ("realizado")
def ccminer_api_output(command = b"summary",url = "localhost",port = "4068"): try: tn = Telnet(url,port) tn.write(command) output = tn.read_all().decode("utf-8") tn.write(b"^]") tn.close() print (output) return output except: return None print ("ERROR IN TELNET")
def Fun_Telnet(Host, user, password): tn = Telnet(Host) print("telnet", tn) tn.read_until("login: "******"\n") if password: tn.read_until("Password: "******"\n") tn.write("ls -la \n") tn.write("exit\n") print(tn.read_all())
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 cmd_switch_wireless(ensoapi): """Turn wi-fi on/off""" tn = Telnet(HOST) tn.read_until("login: "******"\n") tn.read_until("Password: "******"\n") tn.write("".join(("ifconfig ", IFACE, "\n"))) tn_out = tn.read_until("Interrupt") cmd = "" if tn_out.find(" UP ") != -1: cmd = " down" else: cmd = " up" if len(cmd) != 0: tn.write("".join(("ifconfig ", IFACE, cmd, "\n"))) tn.write("exit\n") tn.read_all()
def cmd_switch_wireless(ensoapi): """Turn wi-fi on/off""" tn = Telnet(HOST, 23) tn.read_until(b"login: "******"\n") tn.read_until(b"Password: "******"\n") tn.write("".join((b"ifconfig ", IFACE, "\n"))) tn_out = tn.read_until(b"Interrupt") cmd = b"" if tn_out.find(b" UP ") != -1: cmd = b" down" else: cmd = b" up" if len(cmd) != 0: tn.write(b"".join((b"ifconfig ", IFACE, cmd, b"\n"))) tn.write("exit\n") tn.read_all()
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
def handler(self, **args): "Grabs an excuse from the BOFH excuse server" from telnetlib import Telnet connection=Telnet("athena.jive.org", 666) text = "" text = connection.read_all() #i = connection.read_some() #while i != "": # text = text + i # i = connection.read_some() connection.close() text = text.split("\n") from string import join msg = join(text[3:-1]) # The first three lines and the last are unneeded from irclib import Event target = self.return_to_sender(args) return Event("privmsg", "", target, [msg])
def status(self): status = initdv2.Status.UNKNOWN if self.socks: ip, port = self.socks[0].conn_address try: telnet = Telnet(ip, port) except: return status telnet.write("HEAD / HTTP/1.0\n\n") if "server: nginx" in telnet.read_all().lower(): return initdv2.Status.RUNNING return initdv2.Status.UNKNOWN else: args = [self.initd_script, "status"] _, _, returncode = system2(args, raise_exc=False) if returncode == 0: return initdv2.Status.RUNNING else: return initdv2.Status.NOT_RUNNING
def _send_command(self, torrent): telnet = Telnet() try: telnet.open(self.host, int(self.port)) except socket.error: raise TorrentServerConnectException try: telnet.read_until(">") telnet.write("auth %s %s\n" % (str(self.username), str(self.passwd))) telnet.read_until(">") telnet.write("dllink %s\n" % str(torrent)) telnet.write("quit\n") session = telnet.read_all() if "Bad login" in session: raise TorrentAuthException elif "exception" in session: raise TorrentURLException finally: telnet.close()
def handler(self, **args): """gets an insult""" from telnetlib import Telnet connection=Telnet("insulthost.colorado.edu", 1695) connection.write("\n") text="" #i=connection.read_some() #while i != '': # text = text + i # i=connection.read_some() text = connection.read_all() import string who = args["text"] who = who[string.find(who, " ")+1:] who = who[string.find(who, " ")+1:] text = string.replace(text, "You are", who + " is") from irclib import Event target = self.return_to_sender(args) result = Event("privmsg", "", target, [ text ]) return result
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import urllib from telnetlib import Telnet TCP_IP = '127.0.0.1' TCP_PORT = 1234 BUFFER_SIZE = 10024 url = "http://resolver.kb.nl/resolve?urn=ddd:010041671:mpeg21:a0005:ocr" MESSAGE = urllib.urlopen(url).read().replace('\n','').replace('\r','') + "\n" tn = Telnet(TCP_IP, TCP_PORT) tn.write(MESSAGE) data = tn.read_all() for line in data.split(): if not line.split('/')[1] == "O" and not line.find('MISC') > -1: print line
incorrect_password = telnet.read_until(b"Try again :", 30).decode("utf-8").rstrip().endswith("Try again :") if incorrect_password is not True: break j += 1 if j >= len(words2): continue combination = words1[i]+"-"+words2[j] print(combination) telnet.write(combination.encode('ascii') + b"\n") incorrect_password = telnet.read_until(b"return later.", 30).decode("utf-8").rstrip().endswith("return later.") if incorrect_password is not True: break telnet.read_all() telnet.open(host=hostname, port=port) j += 1 else: i += 1 continue break telnet.close() print("Username:"******"Password:", combination)
class Emulator(Device): logcat_proc = None port = None proc = None telnet = None def __init__(self, app_ctx, arch, resolution=None, sdcard=None, userdata=None, no_window=None, binary=None, **kwargs): Device.__init__(self, app_ctx, **kwargs) self.arch = ArchContext(arch, self.app_ctx, binary=binary) self.resolution = resolution or '320x480' self.sdcard = None if sdcard: self.sdcard = self.create_sdcard(sdcard) self.userdata = tempfile.NamedTemporaryFile(prefix='qemu-userdata') self.initdata = userdata if userdata else os.path.join(self.arch.sysdir, 'userdata.img') self.no_window = no_window self.battery = EmulatorBattery(self) self.geo = EmulatorGeo(self) self.screen = EmulatorScreen(self) @property def args(self): """ Arguments to pass into the emulator binary. """ qemu_args = [self.arch.binary, '-kernel', self.arch.kernel, '-sysdir', self.arch.sysdir, '-data', self.userdata.name, '-initdata', self.initdata, '-wipe-data'] if self.no_window: qemu_args.append('-no-window') if self.sdcard: qemu_args.extend(['-sdcard', self.sdcard]) qemu_args.extend(['-memory', '512', '-partition-size', '512', '-verbose', '-skin', self.resolution, '-gpu', 'on', '-qemu'] + self.arch.extra_args) return qemu_args def start(self): """ Starts a new emulator. """ if self.proc: return original_devices = set(self._get_online_devices()) qemu_log = None qemu_proc_args = {} if self.logdir: # save output from qemu to logfile qemu_log = os.path.join(self.logdir, 'qemu.log') if os.path.isfile(qemu_log): self._rotate_log(qemu_log) qemu_proc_args['logfile'] = qemu_log else: qemu_proc_args['processOutputLine'] = lambda line: None self.proc = ProcessHandler(self.args, **qemu_proc_args) self.proc.run() devices = set(self._get_online_devices()) now = datetime.datetime.now() while (devices - original_devices) == set([]): time.sleep(1) if datetime.datetime.now() - now > datetime.timedelta(seconds=60): raise TimeoutException('timed out waiting for emulator to start') devices = set(self._get_online_devices()) devices = devices - original_devices self.serial = devices.pop() self.connect() def _get_online_devices(self): return set([d[0] for d in self.dm.devices() if d[1] != 'offline' if d[0].startswith('emulator')]) def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return Device.connect(self) self.port = int(self.serial[self.serial.rindex('-')+1:]) self.geo.set_default_location() self.screen.initialize() # setup DNS fix for networking self.app_ctx.dm.shellCheckOutput(['setprop', 'net.dns1', '10.0.2.3']) def create_sdcard(self, sdcard_size): """ Creates an sdcard partition in the emulator. :param sdcard_size: Size of partition to create, e.g '10MB'. """ mksdcard = self.app_ctx.which('mksdcard') path = tempfile.mktemp(prefix='sdcard') sdargs = [mksdcard, '-l', 'mySdCard', sdcard_size, path] sd = subprocess.Popen(sdargs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) retcode = sd.wait() if retcode: raise Exception('unable to create sdcard: exit code %d: %s' % (retcode, sd.stdout.read())) return path def cleanup(self): """ Cleans up and kills the emulator. """ Device.cleanup(self) if self.proc: self.proc.kill() self.proc = None # Remove temporary user data image if self.userdata: self.userdata.close() # Remove temporary sdcard if self.sdcard and os.path.isfile(self.sdcard): os.remove(self.sdcard) # TODO this function is B2G specific and shouldn't live here @uses_marionette def wait_for_system_message(self, marionette): marionette.set_script_timeout(45000) # Telephony API's won't be available immediately upon emulator # boot; we have to wait for the syste-message-listener-ready # message before we'll be able to use them successfully. See # bug 792647. print 'waiting for system-message-listener-ready...' try: marionette.execute_async_script(""" waitFor( function() { marionetteScriptFinished(true); }, function() { return isSystemMessageListenerReady(); } ); """) except: # Look for ScriptTimeoutException this way to avoid a # dependency on the marionette python client. exc_name = sys.exc_info()[0].__name__ if exc_name != 'ScriptTimeoutException': raise print 'timed out' # We silently ignore the timeout if it occurs, since # isSystemMessageListenerReady() isn't available on # older emulators. 45s *should* be enough of a delay # to allow telephony API's to work. pass print '...done' # TODO this function is B2G specific and shouldn't live here @uses_marionette def wait_for_homescreen(self, marionette): print 'waiting for homescreen...' marionette.set_context(marionette.CONTEXT_CONTENT) marionette.execute_async_script(""" log('waiting for mozbrowserloadend'); window.addEventListener('mozbrowserloadend', function loaded(aEvent) { log('received mozbrowserloadend for ' + aEvent.target.src); if (aEvent.target.src.indexOf('ftu') != -1 || aEvent.target.src.indexOf('homescreen') != -1 || aEvent.target.src.indexOf('verticalhome') != -1) { window.removeEventListener('mozbrowserloadend', loaded); marionetteScriptFinished(); } });""", script_timeout=300000) print '...done' def _get_telnet_response(self, command=None): output = [] assert(self.telnet) if command is not None: self.telnet.write('%s\n' % command) while True: line = self.telnet.read_until('\n') output.append(line.rstrip()) if line.startswith('OK'): return output elif line.startswith('KO:'): raise Exception('bad telnet response: %s' % line) def _run_telnet(self, command): if not self.telnet: self.telnet = Telnet('localhost', self.port) self._get_telnet_response() return self._get_telnet_response(command) def __del__(self): if self.telnet: self.telnet.write('exit\n') self.telnet.read_all()
def whois(*iplist, **kwargs): ret = list() host = kwargs.get("host") port = kwargs.get("port") or 43 ipv4_whois_list = list() ipv6_whois_list = list() # ip4_list and ip6_list have pairs of network range and # the corresponding whois server, however, need to de-serialize them. with open("ip4_list") as ipv4_file: ipv4_whois_list = list( map(lambda pair: [IP(pair[0]), pair[1]], decode_whoisList(ipv4_file.read())) ) with open("ip6_list") as ipv6_file: ipv6_whois_list = list( map(lambda pair: [IP(pair[0]), pair[1]], decode_whoisList(ipv6_file.read())) ) for ip_str in iplist: ip = IP(ip_str) if len(ip) != 1: raise ValueError( "The given IP address seems to be ranged IP address" ) whoispair = list() if ip.version() == 4: for pair in ipv4_whois_list: if ip in pair[0]: whoispair = pair if host: whoispair[1] = host break elif ip.version() == 6: for pair in ipv6_whois_list: if ip in pair[0]: if host: whoispair[1] = host break else: raise ValueError(("Unknown IP version: {0}").format(ip.version())) if len(whoispair) < 2: raise ValueError("There is no valid whois server.") telnet = Telnet( server_map.get(whoispair[1]) or whoispair[1], port ) if whoispair[1] != "whois.nic.ad.jp": telnet.write(("{0}\n").format(ip_str).encode("utf-8")) else: telnet.write(("{0}/e\n").format(ip_str).encode("utf-8")) result = telnet.read_all().decode("utf-8") telnet.close() del telnet if whoispair[1] in ["arin", server_map["arin"]]: result = decode_arin(result) ref = result.get("ReferralServer") # Sometimes, arin returns ReferralServer to redirect to the # corresponding whois... if ref: parsed_url = urlparse(ref) (redirected_host, redirected_port) = \ parsed_url.netloc.split(":") result = whois(ip_str, host=redirected_host, port=redirected_port) if len(result) > 0: result = result[0] elif whoispair[1] in ["apnic", server_map["apnic"]]: result = decode_apnic(result) elif whoispair[1] in ["afrinic", server_map["afrinic"]]: result = decode_afrinic(result) elif whoispair[1] in ["lacnic", server_map["lacnic"]]: result = decode_lacnic(result) elif whoispair[1] in ["ripe", server_map["ripe"]]: result = decode_ripe(result) elif whoispair[1] == "rwhois.gin.ntt.net": raise NotImplementedError("rwhois protocol is not supported") elif whoispair[1] == "twnic": raise ValueError("This NIC doesn't provide detailed information") elif whoispair[1] == "whois.nic.ad.jp": result = decode_jpnic(result) elif whoispair[1] == "whois.nic.ad.br": raise ValueError("This NIC shows illegal string") elif whoispair[1] == "whois.nic.or.kr": result = decode_krnic(result) # If there is no perser, add result as-is. ret.append(result) return ret
def _read_stats(self): connection = Telnet(self._server, self._port, timeout=30) connection.write('stats\n') connection.write('quit\n') self._stats_raw = connection.read_all()
from telnetlib import Telnet import os #os.system('/root/cogbuntu-11.10/ochack/bin/opencog/server/cogserver -c /root/cogbuntu-11.10/ochack/lib/opencog.conf &') tn = Telnet('localhost', 17001) tn.write("scm\n") #tn.write('(load-scm-from-file "tests/reasoning/pln/smalldemo.scm")\n') tn.write('(load-scm-from-file "/root/custom/opencog/demodata/truck.scm")\n') tn.write(".\n") tn.write("list\n") tn.write("exit\n") #tn.write("shutdown\n") print tn.read_all()
__author__ = 'TIW' from telnetlib import Telnet tn = Telnet('10.0.0.1') tn.read_until('Username:'******'ascii')) tn.write('cisco'.encode('ascii') + b"\n") tn.write('cisco'.encode('ascii') + b"\n") tn.read_until('en:'.encode('ascii') + b"\n") tn.write('cisco'.encode('ascii') + b"\n") tn.write('show run'.encode('ascii') + b"\n") print(tn.read_all()) tn.close()
class BaseEmulator(Device): port = None proc = None telnet = None def __init__(self, app_ctx, **kwargs): self.arch = ArchContext(kwargs.pop('arch', 'arm'), app_ctx, binary=kwargs.pop('binary', None), avd=kwargs.pop('avd', None)) super(BaseEmulator, self).__init__(app_ctx, **kwargs) self.tmpdir = tempfile.mkdtemp() # These rely on telnet self.battery = EmulatorBattery(self) self.geo = EmulatorGeo(self) self.screen = EmulatorScreen(self) @property def args(self): """ Arguments to pass into the emulator binary. """ return [self.arch.binary] def start(self): """ Starts a new emulator. """ if self.proc: return original_devices = set(self._get_online_devices()) # QEMU relies on atexit() to remove temporary files, which does not # work since mozprocess uses SIGKILL to kill the emulator process. # Use a customized temporary directory so we can clean it up. os.environ['ANDROID_TMP'] = self.tmpdir qemu_log = None qemu_proc_args = {} if self.logdir: # save output from qemu to logfile qemu_log = os.path.join(self.logdir, 'qemu.log') if os.path.isfile(qemu_log): self._rotate_log(qemu_log) qemu_proc_args['logfile'] = qemu_log else: qemu_proc_args['processOutputLine'] = lambda line: None self.proc = ProcessHandler(self.args, **qemu_proc_args) self.proc.run() devices = set(self._get_online_devices()) now = datetime.datetime.now() while (devices - original_devices) == set([]): time.sleep(1) # Sometimes it takes more than 60s to launch emulator, so we # increase timeout value to 180s. Please see bug 1143380. if datetime.datetime.now() - now > datetime.timedelta( seconds=180): raise TimeoutException( 'timed out waiting for emulator to start') devices = set(self._get_online_devices()) devices = devices - original_devices self.serial = devices.pop() self.connect() def _get_online_devices(self): return [d[0] for d in self.dm.devices() if d[1] != 'offline' if d[0].startswith('emulator')] def connect(self): """ Connects to a running device. If no serial was specified in the constructor, defaults to the first entry in `adb devices`. """ if self.connected: return super(BaseEmulator, self).connect() serial = self.serial or self.dm._deviceSerial self.port = int(serial[serial.rindex('-') + 1:]) def cleanup(self): """ Cleans up and kills the emulator, if it was started by mozrunner. """ super(BaseEmulator, self).cleanup() if self.proc: self.proc.kill() self.proc = None self.connected = False # Remove temporary files if os.path.isdir(self.tmpdir): shutil.rmtree(self.tmpdir) def _get_telnet_response(self, command=None): output = [] assert self.telnet if command is not None: self.telnet.write('%s\n' % command) while True: line = self.telnet.read_until('\n') output.append(line.rstrip()) if line.startswith('OK'): return output elif line.startswith('KO:'): raise Exception('bad telnet response: %s' % line) def _run_telnet(self, command): if not self.telnet: self.telnet = Telnet('localhost', self.port) self._get_telnet_response() return self._get_telnet_response(command) def __del__(self): if self.telnet: self.telnet.write('exit\n') self.telnet.read_all()
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 ])