Python paramiko.py3compat.u() Examples

The following are 17 code examples of paramiko.py3compat.u(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko.py3compat , or try the search function .
Example #1
Source File: hostkeys.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
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', '') 
Example #2
Source File: test_sftp.py    From python-hpedockerplugin with Apache License 2.0 6 votes vote down vote up
def test_D_flush_seek(self):
        """
        verify that buffered writes are automatically flushed on seek.
        """
        try:
            with sftp.open(FOLDER + '/happy.txt', 'w', 1) as f:
                f.write('full line.\n')
                f.write('partial')
                f.seek(9, f.SEEK_SET)
                f.write('?\n')

            with sftp.open(FOLDER + '/happy.txt', 'r') as f:
                self.assertEqual(f.readline(), u('full line?\n'))
                self.assertEqual(f.read(7), b'partial')
        finally:
            try:
                sftp.remove(FOLDER + '/happy.txt')
            except:
                pass 
Example #3
Source File: test_sftp.py    From python-hpedockerplugin with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def keygen(self,
               filename: str,
               type: str = 'rsa',
               bits: int = 4096,
               comment: Optional[str] = None,
               passphrase: Optional[str] = None) -> SSHKeygenResponse:
        """
        Generate an SSH keypair.

        :param filename: Output file name for the private key (the public key will be stored in <filename>.pub).
        :param type: Encryption algorithm, either "rsa" or "dsa" (default: "rsa").
        :param bits: Key length in bits (default: 4096).
        :param comment: Key comment (default: None).
        :param passphrase: Key passphrase (default: None).
        :return: :class:`platypush.message.response.ssh.SSHKeygenResponse`.
        """
        assert type != 'dsa' or bits <= 1024, 'DSA keys support a maximum of 1024 bits'
        assert type in self.key_dispatch_table, 'No such type: {}. Available types: {}'.format(
            type, self.key_dispatch_table.keys())

        if filename:
            filename = os.path.abspath(os.path.expanduser(filename))

        prv = self.key_dispatch_table[type].generate(bits=bits)
        prv.write_private_key_file(filename=filename, password=passphrase)
        pub = self.key_dispatch_table[type](filename=filename, password=passphrase)
        pub_file = '{filename}.pub'.format(filename=filename)
        with open(pub_file, 'w') as f:
            f.write('{name} {key}'.format(name=pub.get_name(), key=pub.get_base64()))
            if comment:
                f.write(' ' + comment)

        hash = u(hexlify(pub.get_fingerprint()))
        return SSHKeygenResponse(fingerprint=hash, key_file=filename, pub_key_file=pub_file) 
Example #5
Source File: poc.py    From pub with GNU General Public License v2.0 5 votes vote down vote up
def set_host_key(self, host_key):
        self.host_key = host_key
        LOG.info('ServerHostKey: %s'%u(hexlify(host_key.get_fingerprint()))) 
Example #6
Source File: pkey.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
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', '') 
Example #7
Source File: message.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def get_text(self):
        """
        Fetch a Unicode string from the stream.
        """
        return u(self.get_string()) 
Example #8
Source File: packet.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def readline(self, timeout):
        """
        Read a line from the socket.  We assume no data is pending after the
        line, so it's okay to attempt large reads.
        """
        buf = self.__remainder
        while not linefeed_byte in buf:
            buf += self._read_timeout(timeout)
        n = buf.index(linefeed_byte)
        self.__remainder = buf[n + 1:]
        buf = buf[:n]
        if (len(buf) > 0) and (buf[-1] == cr_byte_value):
            buf = buf[:-1]
        return u(buf) 
Example #9
Source File: demo_server.py    From stream with MIT License 5 votes vote down vote up
def check_auth_publickey(self, username, key):
        self.plog("check_auth_publickey: username='%s', key fingerprint='%s'" % (
            username, u(hexlify(key.get_fingerprint()))
        ))
        return paramiko.AUTH_FAILED 
Example #10
Source File: sftp_client.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #11
Source File: sshserver.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def check_auth_publickey(self, username, key):
        print('Auth attempt with username: {!r} & key: {!r}'.format(username, u(hexlify(key.get_fingerprint())))) # noqa
        if (username in ['robey', 'keyonly']) and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED 
Example #12
Source File: fungsi.py    From txtool with GNU General Public License v2.0 5 votes vote down vote up
def ssh_shell(command):
    from paramiko.py3compat import u
    oldtty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        command.settimeout(0.0)
        while True:
            r, w, e = select.select([command, sys.stdin], [], [])
            if command in r:
                try:
                    x = u(command.recv(1024))
                    if len(x) == 0:
                        sys.stdout.write('\r\n{0}[x]{1} shell closed'.format(warna.merah, warna.tutup))
                        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
                command.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) 
Example #13
Source File: demo_server.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
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 
Example #14
Source File: interactive.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
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)

    
# thanks to Mike Looijmans for this code 
Example #15
Source File: helpers.py    From decrypt-ios-apps-script with MIT License 5 votes vote down vote up
def interactive_shell(chan, callback=None):
    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[+] Terminating SSH connection\r\n")
                        sys.stdout.flush()
                        if callback != None:
                            callback()
                        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) 
Example #16
Source File: test_sftp.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def test_5a_posix_rename(self):
        """Test posix-rename@openssh.com 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 
Example #17
Source File: sshserver.py    From webssh with MIT License 5 votes vote down vote up
def check_auth_publickey(self, username, key):
        print('Auth attempt with username: {!r} & key: {!r}'.format(username, u(hexlify(key.get_fingerprint())))) # noqa
        if (username in ['robey', 'keyonly']) and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        if username == 'pkey2fa' and key == self.good_pub_key:
            self.key_verified = True
            return paramiko.AUTH_PARTIALLY_SUCCESSFUL
        return paramiko.AUTH_FAILED