Example #1
0
File: vtom.py Project: minoue/VtoM
    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"
Example #2
0
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
Example #3
0
File: Port.py Project: flowsha/zhwh
 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 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)
Example #5
0
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('"')
Example #6
0
def attempt(host, port, timeout, outputFile, secondCall = False):
	try:
		tn = Telnet(host,port,timeout)
		tn.open(host,port,timeout)
		header = tn.read_some()
		tn.close()
		print "[!] Port %d seems to be open on %s" %(port,host)
		file = open(outputFile, 'a') #writes to file
		file.write("%s:%d"%(host,port))
		if header != "":
			file.write(" - %s"%(header))
		file.write("\n")
		file.close()
	except Exception, e:
		try:
			e[1]
			code, reason = e.args
			print "[ERROR] %s on %s:%d (%d)" %(reason,host,port,code)
		except IndexError:
			if e.args[0] == "timed out" and port in commonOpenPorts:
				if secondCall is False:
					print "[!] extending timeout on common port (%d)" %(port)
					return attempt(host, port, (timeout*2), outputFile, True)
			
			#only write timeouts to the file
			if e.args[0] == "timed out":
				file = open(outputTimeoutFile, 'a') #writes to file
				file.write("%s:%d"%(host,port))
				
				file.write("\n")
				file.close()
			print "[ERROR] %s on %s:%d " %(e.args[0],host,port)
Example #7
0
def upnpbind(ex_port=None):
    location = search_device()
    in_ip = get_internal_ip_address(location)
    control_url = get_control_url(location)
    ex_ip = get_external_ip_address(control_url)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((in_ip, 0))
    s.listen(1)
    in_addr = s.getsockname()
    if ex_port:
        ex_addr = (ex_ip, ex_port)
    else:
        ex_addr = (ex_ip, in_addr[1])
    print >>sys.stderr, "[+] bind: %r" % (in_addr,)

    add_port_mapping(control_url, ex_addr, in_addr)

    try:
        c, remote_addr = s.accept()
        print >>sys.stderr, "[+] accept: %r" % (remote_addr,)
        s.close()

        t = Telnet()
        t.sock = c
        t.interact()
        t.close()
    finally:
        delete_port_mapping(control_url, ex_addr)
Example #8
0
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 QYT_TelnetClient(ip, 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'+b' '*15)
		result= tn.expect([],timeout=1)[2].decode()
		# print(rackreply)
		# time.sleep(1)
	tn.write(b'exit\n')
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	print(rackreply)
	tn.close()
	return result
 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])
Example #11
0
 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
Example #12
0
File: Port.py Project: flowsha/zhwh
 def show(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 range(1,7):
             if params[i+7] <> "":
                 tn.write(params[i+7] + "\n")
                 if "show board" in params[i+7]: tn.write(" ")
                 elif "slot" in params[i+7]:
                     print(tn.read_until("quit>", self.cmdTimeout)),
                     tn.write(" ")
                 elif "display" in params[i+7]:
                     print(tn.read_until(":", self.cmdTimeout)),
                     tn.write("\n   ")
                 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()
Example #13
0
File: mpd.py Project: lejenome/lyvi
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 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)
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()
Example #16
0
def takeover_light(ip):
    t = Telnet()
    t.open(ip, 30000)
    t.write("[Link,Touchlink]")
    output = t.read_until("[Link,Touchlink,success", 10)
    print output
    t.close()
Example #17
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()
Example #18
0
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
Example #19
0
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
Example #20
0
    def sendTo(self, hosts=None, default_port=1000, module=0, msg=None):
        """
        Send the message to the DEP.

        If the argument 'hosts' is an IP or a list of IP's, it iterate over them to have an answer.
        If the argument 'hosts' is an instance of DEPMessage, it uses the hosts known in the instance.
        Open a connection to the DEP, sends the message and return the answer
        in a synchronous manner.
        """
        if msg:
            self.message = msg
        self.module = module
        telnet = Telnet()
        # t.set_debuglevel(100)
        if isinstance(hosts, str):
            hosts = (hosts,)
        elif isinstance(hosts, DEPMessage):
            self._hosts = hosts._hosts
            hosts = self._hosts.keys()

        for host in hosts or self.hosts:
            try:
                if host in self._hosts and self._hosts[host]:
                    telnet = self._hosts[host]
                else:
                    logger.info('%s not active in %r', host, self._hosts)
                    if ':' in host:
                        telnet.open(*host.split(':'))
                    else:
                        telnet.open(host, default_port)
                    self._hosts[host] = telnet
                sock = telnet.get_socket()
                msg = self._build()
                bytessent = sock.send(msg)
                logger.debug('%d chars sent', bytessent)
                answer, size = b'', None
                while True:
                    answer += sock.recv(4096)
                    if not size and len(answer) >= 4:
                        size = int(codecs.encode(answer[:4][::-1], 'hex'), 16)
                    if len(answer) >= size:
                        break
                    readsel, _, _ = select([sock], [], [], 0.5)
                    if len(readsel) == 0:
                        answer += telnet.read_very_lazy()
                        break
                break
            except socket.error:
                telnet.close()
                self._hosts[host] = None
                logger.exception('Socket issue with %s', host)
                continue
        else:
            raise ValueError('No dep available in the list : ' +
                             str(hosts or self._hosts))
        self.current_answer = codecs.encode(answer, 'hex').decode().upper()
        if LOG_DEPCALLS:  # pragma: no cover
            with open('result.txt', 'ab') as out:
                out.write(b'>>' + codecs.encode(msg[13:], 'hex').upper() + b':' + self.current_answer.encode().upper() + b'\n')
        return self.current_answer
Example #21
0
 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()
Example #22
0
    def set_state(self, state):
        s = 'On' if state else 'Off'

        tel = Telnet(self.bar.host)

        try:
            time.sleep(2.)

            garbage = tel.read_very_eager()
            print('GarbageRead:', garbage)

            w = "/%s %d" % (s, self.ident)
            msg = w.encode('ascii') + b"\r\n"
            print("Writing:", repr(msg))
            tel.write(msg)

            print("Reading:", repr(tel.read_until("NPS>", timeout=5)))

            time.sleep(1.)
            garbage = tel.read_very_eager()
            print('GarbageRead2:', garbage)

            self.state = state
        finally:
            tel.close()

        del tel

        time.sleep(0.5)
Example #23
0
    def listen(self, port=4444, echotest=False):
        check_cmd = 'echo "\x1b[32mgot a shell!\x1b[0m"'  # green

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', port))  # the empty string represents INADDR_ANY
        s.listen(1)

        if isinstance(self.p, Popen):
            addrinfo = socket.getaddrinfo('localhost', port, socket.AF_INET, socket.SOCK_STREAM)
            host = addrinfo[0][4][0]
        else:
            host = self.p.getsockname()[0]
        yield (host, port)

        c, addr = s.accept()
        s.close()
        if echotest:
            c.sendall(check_cmd + '\n')
            sys.stdout.write(c.recv(8192))

        t = Telnet()
        t.sock = c
        t.interact()
        t.close()
        self.close()
def QYT_TelnetClient(ip, username, password, cmd):
	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('terminal length 0'.encode() + b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)

	tn.write(cmd.encode() + b'\n')
	time.sleep(1)
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)
	result = rackreply
	time.sleep(1)
	tn.write(b'exit\n')
	rackreply = tn.expect([],timeout=1)[2].decode().strip()
	#print(rackreply)
	tn.close()
	return result
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()
Example #26
0
 def testRcptWithoutMail(self):
     """The RCPT command must be preceded by the MAIL command."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('RCPT TO:<*****@*****.**>')
     self.assertEqual(client.read_some(), '503 Error: need MAIL command\r\n')
     client.close()
Example #27
0
 def testDataWithoutRcpt(self):
     """The DATA command must be preceded by the RCPT TO: command."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('DATA')
     self.assertEqual(client.read_some(), '503 Error: need RCPT command\r\n')
     client.close()
Example #28
0
 def testLegalHelo(self):
     """The server responds to a valid HELO command."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('HELO localhost')
     self.assertEqual(client.read_some(), '250 test Hello 127.0.0.1\r\n')
     client.close()
Example #29
0
 def testIllegalHelo(self):
     """HELO takes a single argument."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('HELO')
     self.assertEqual(client.read_some(), '501 Syntax: HELO hostname\r\n')
     client.close()
Example #30
0
    def testMultipleHelo(self):
        """Only a single HELO command is allowed per connection."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('HELO localhost')
        self.assertEqual(client.read_some(), '250 test Hello 127.0.0.1\r\n')
        client.write('HELO localhost')
        self.assertEqual(client.read_some(), '503 Duplicate HELO/EHLO\r\n')
        client.close()
Example #31
0
    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
Example #32
0
def postMortem(sim, sim_node_id, device_type, host, port):
    "Post mortem mode... interact direct with the console and log to file."
    st = DEVICES.get(device_type)
    if st is None:
        sim.log(logging.CRITICAL, 'postMortem: unknown device type [%s]' % device_type)
        return

    username, password, secret, init_cmd, show_cmd = st

    if sim is not None:
        fh = open("pm-%s-%s.log" % (sim.simId, sim_node_id), "w")
    else:
        import sys
        fh = sys.stdout

    try:
        tn = Telnet(host, port)
    except socket_error as e:
        fh.write(st)
        fh.write(str(e))
    else:
        sendLine(tn, UPRMPT + PROMPT, CRLF)

        if LastMatch is None:
            fh.write('can\'t get a response!')
            fh.close()
            tn.close()
            return

        # login prompt?
        if myMatch(UPRMPT, LastMatch):
            sendLine(tn, PPRMPT, username)
            sendLine(tn, PROMPT, password)

        # need to enable?
        if myMatch(NOPRIV, LastMatch):
            sendLine(tn, PPRMPT, 'enable')
            sendLine(tn, PROMPT, secret)

        # send the initialization (term length etc.)
        for line in init_cmd:
            sendLine(tn, PROMPT, line)

        # send the actual show commands
        for line in show_cmd:
            p = sendLine(tn, PROMPT, line)
            if p is not None:
                fh.write(p)

        # close session (should work across the board)
        sendLine(tn, [b'.*'], 'exit')
        tn.close()

    fh.close()
Example #33
0
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()
Example #34
0
    def testRcptWithoutTo(self):
        """The RCPT command must contain TO:<address> as the argument."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('RCPT')
        self.assertEqual(client.read_some(),
                         '501 Syntax: RCPT TO: <address>\r\n')
        client.close()
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()
Example #36
0
    def testRcptEmptyTo(self):
        """The RCPT command cannot have an empty TO:."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('RCPT TO:')
        self.assertEqual(client.read_some(),
                         '501 Syntax: RCPT TO: <address>\r\n')
        client.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
Example #38
0
    def testDuplicateMailCommand(self):
        """Nested MAIL commands are not allowed."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(),
                         '503 Error: nested MAIL command\r\n')
        client.close()
Example #39
0
 def send_command(self, command):
     try:
         tvConnection = Telnet(self.ip, LG_WEBOS_CONTROL_PORT)
         print(tvConnection.read_eager().decode('ascii'))
         print("Command is: " + command)
         print(command.encode('ascii') + b"\n")
         tvConnection.write(command.encode('ascii') + b"\r\n")
         print(tvConnection.read_eager().decode('ascii'))
         tvConnection.close()
     except:
         print("Could not connect to TV")
Example #40
0
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()
Example #41
0
    def testMultipleRcpts(self):
        """Multiple RCPT commands can be issued to add recipients."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')

        for rcpt in self.addrs:
            client.write('RCPT TO:<%s>' % rcpt)
            self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.close()
Example #42
0
    def testDataArgument(self):
        """The DATA command does not take any arguments."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('RCPT TO:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('DATA some data here')
        self.assertEqual(client.read_some(), '501 Syntax: DATA\r\n')
        client.close()
Example #43
0
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
Example #44
0
    def ping(host: str, port: int) -> bool:
        success = True
        test: Telnet = None
        try:
            test = Telnet(host, port)
            test.close()
        except Exception as e:
            success = False
        return success


#endregion
Example #45
0
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
Example #46
0
def telnet_test(host, port, user, password, timeout):
    tn = Telnet(host=host, port=port, timeout=timeout)
    time.sleep(1)
    tn.read_until(b"login: "******"utf-8") + b"\n")
    time.sleep(timeout)
    tn.read_until(b"Password: "******"utf-8") + b"\n")
    time.sleep(timeout)
    yield tn.read_very_eager()
    tn.close()
    yield "Done"
Example #47
0
def runTELNET (ip,port):

    session = Telnet()

    try:
        session.open(ip, port)
        session.close()
        return "PASSED"

    except Exception as e:
        session.close()
        return e
Example #48
0
class TelnetClient(object):
    """docstring for TelnetClient"""
    def __init__(self, addr, port=23):
        self.addr = addr
        self.port = port
        self.tn = None

    # 连接对象
    def start(self):
        # 人为抛出异常
        raise Exception('Telnet Exception')

        #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):
        pass

    # 实现上下文管理
    def __enter__(self):
        # 创建连接
        self.tn = Telnet(self.addr, self.port)
        # 队列存储用户历史记录
        self.history = deque()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('IN __exit__')
        self.tn.close()
        self.tn = None
        with open(self.addr + '_history.txt', 'w') as f:
            f.writelines(self.history)
Example #49
0
File: hydra.py Project: dpep/hydra
class TelnetHacker(Hacker):
    @staticmethod
    def getServiceName():
        return 'telnet'

    def init(self):
        self.server = args.server
        self.client = Telnet()

    def attempt(self, login, password):
        if args.verbose:
            msg = '%s / %s  @  %s' % (login, password, self.server)
            self.log(msg)
        if args.debug:
            return False

        try:
            self.client.open(self.server, port=args.port, timeout=args.timeout)
            self.client.read_until('login: '******'Password: '******'"%s"' % msg
            if 'incorrect' in msg:
                return False

            # double check that we're in fact logged in
            cmd = 'echo $?'
            self.client.write(cmd + "\n")
            time.sleep(.1)
            msg = self.client.read_eager()
            if not msg.startswith(cmd):
                raise Exception('unexpected response: ' + msg)
            print '"%s"' % msg
            msg = msg[len(cmd):].strip(" \r\n")
            print '"%s"' % msg
            if not msg:
                # or did we timeout?
                return False

            if msg[0] in ['0', '1']:
                return True

            if msg[-1] in ['0', '1']:
                return True

        finally:
            self.client.close()
Example #50
0
    def testDataResponse(self):
        """The DATA instructs the client to end the message with <CR><LF>.<CR><LF>."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('RCPT TO:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.write('DATA')
        self.assertEqual(client.read_some(),
                         '354 End data with <CR><LF>.<CR><LF>\r\n')
        client.close()
Example #51
0
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")
Example #52
0
File: dump.py Project: ZIllR0/ctf-1
def worker(_):
    xs = []
    ys = []
    r = Telnet('reality.ctfcompetition.com', 1337)
    r.read_until(b'coefficients')
    for _ in range(3):
        r.read_until(b': ')
        c = r.read_until(b'\n').decode()
        x, y = c.split(', ')
        xs.append(x)
        ys.append(y)
    r.close()
    return xs, ys
Example #53
0
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(b"login: "******"Password: "******"$ ")
        stdout.write(t.decode())
        while True:
            uinput = stdin.readline()
            if not uinput:
                break
            self.history.append(uinput)
            self.tn.write(uinput.encode())
            t = self.tn.read_until(b"$ ").decode()
            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):
        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)
        if exc_type:  # 模拟处理异常
            print(exc_tb)
            return True
Example #54
0
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: ")
        stdout.write(t)
        user = stdin.readline()
        self.tn.write(user)

        #password
        t = self.tn.read_until('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 get_cluster_info(host, port, ignore_cluster_errors=False):
    """
    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) not in [2, 3] 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)
    regex_index, match_object, res = client.expect(
        [re.compile(b'\n\r\nEND\r\n'),
         re.compile(b'ERROR\r\n')])
    client.close()

    if res == b'ERROR\r\n' and ignore_cluster_errors:
        return {
            'version': version,
            'nodes': ['{0}:{1}'.format(smart_text(host), smart_text(port))]
        }

    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('{0}:{1}'.format(smart_text(ip or host),
                                          smart_text(port)))
    except ValueError:
        raise WrongProtocolData(cmd, res)
    return {'version': version, 'nodes': nodes}
Example #56
0
class TelnetClient:
    """
    An interface for issuing and interpretting commands over telnet
    """
    timeout = 15
    port = 23

    def __init__(self, host, user=None, passwd=None):
        self.connected = False
        self.loggedin = False
        self.user = user
        self.passwd = passwd

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

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

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

            index, _, _ = self.conn.expect([r'\$ ', r'Password'])
            if index == 0:
                self.loggedin = True

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.write("exit\n")
        self.conn.close()

    def ls(self, *files):
        self.conn.write("ls -la {0}\n".format(' '.join(files)))
        response = self.conn.read_until("$ ")

        output = response.split('\n')[1:-1]
        files = []
        for line in output:
            if line.startswith('total'):
                continue
            files.append(FileListing(line))

        return files
        # No error chevking, because this is a dumb client

    def cd(self, directory):
        self.conn.write("cd {0}\n".format(directory))
        response = self.conn.read_until("$ ")
Example #57
0
def SAM7X_telnet(ip_addr, cmd, *args):
    '''
    Обратиться по протоколу telnet к устройству %ip_addr% и выполнить команду %cmd%
    @param ip_addr - ip-адрес устройства
    @param cmd - команда
    @return результат выполнения команды cmd
    '''
    if len(args):
        cmd = ' '.join([cmd] + list(args))
        cmd = cmd.strip()
    if not ping(ip_addr):
        print('Failed to ping  %s' % ip_addr)
        return
    try:
        tn = Telnet(ip_addr)
        tn.read_until(b'#> ', 2)
        cmd += '\n'
        tn.write(cmd.encode('ascii'))
        s = tn.read_until(b'#> ', 2)
        tn.close()
        '''
        try:
            tn.write(b'exit\n')
            tn.read_until(b'#> ', 2)
            tn.close()
        except:
            pass
        '''
        def splitstr(s, b):
            r = re.compile(b)
            ss = r.split(s)
            ss = list(filter(lambda x: len(x), ss))
            return ss

        s = s.decode('ascii')
        ss = splitstr(s, '[\[\] \t\n\r:]+')
        ss0 = ss[0]
        if ss0 in ['0', '1']:
            ss = splitstr(s, '[\t\n\r]+')
            ss1 = ss[0]
            ss1 = ss1.replace('[%s]' % ss0, '')
            ss1 = ss1.strip()
            return ss1
        ss = s.split('\n')
        print('Failed to parse', ss)
        return
    except:
        print('telnet error')
        #print(sys.exc_info())
        return
def ban_from_cache(targets, is_exact=False):
    # ignore if developing against local db
    if 'localhost' in os.environ['NEX2_URI']:
        return
    if is_exact:
        command_exp = '=='
    else:
        command_exp = '~'
    command = 'ban req.url ' + command_exp + ' '
    for server in cache_urls:
        tn = Telnet(server.replace('http://', ''), '6082')
        for x in targets:
            tn.write(command + x + '\n')
        tn.close()
Example #59
0
def main(host, port):
    telnet = Telnet()
    telnet.open(host, port)

    reader = ReaderThread(telnet)
    reader.start()

    while 1:
        if not reader.isAlive(): break
        line = raw_input()
        telnet.write(line + '\n')
        time.sleep(0.3)

    telnet.close()
Example #60
-1
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)