How to use the paramiko.Transport function in paramiko

To help you get started, we’ve selected a few paramiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ShichaoMa / exec_cmd / execute_cmd.py View on Github external
def get_sftp(self, src):
        host, port, user, password, path = "local", None, None, None, None
        try:
            if src.count("|") == 4:
                host, port, user, password, path = [x.strip() for x in src.split("|")]
                t = paramiko.Transport((host, int(port)))
                t.connect(username=user, password=password)
                sftp = paramiko.SFTPClient.from_transport(t)
            else:
                path = src.strip()
                sftp = None
            return sftp, path, host
        except paramiko.AuthenticationException:
            self.logger.error("Authentication failed")
            self.logger.error("host:%s, port:%s, user:%s, password:%s" % (host, port, user, password))
            exit(1)
        except Exception:
            self.logger.error("error heppened in %s Error:%s"%(host, traceback.format_exc()))
github jumpserver / coco / coco / sshd.py View on Github external
def handle_connection(self, sock, addr):
        logger.debug("Handle new connection from: {}".format(addr))
        transport = paramiko.Transport(sock, gss_kex=False)
        try:
            transport.load_server_moduli()
        except IOError:
            logger.warning("Failed load moduli -- gex will be unsupported")

        transport.add_server_key(self.host_key)
        transport.set_subsystem_handler(
            'sftp', paramiko.SFTPServer, SFTPServer
        )
        connection = Connection.new_connection(addr=addr, sock=sock)
        server = SSHInterface(connection)
        try:
            transport.start_server(server=server)
            transport.set_keepalive(60)
            while transport.is_active():
                chan = transport.accept()
github OpenSourceEconomics / respy / development / analyses / robust / ambiguity_choices / modules / update.py View on Github external
def get_results(is_all):
    """ Get results from server.
    """
    # Starting with clean slate
    cleanup()

    # Read private keys
    key = paramiko.RSAKey.from_private_key_file(KEY_DIR)

    # Open a transport
    transport = paramiko.Transport(('acropolis.uchicago.edu', 22))
    transport.connect(username='eisenhauer', pkey=key)

    # Initialize SFTP connection
    sftp = paramiko.SFTPClient.from_transport(transport)

    # Get files
    sftp.chdir(CLIENT_DIR)

    # Get results directory, this is always downloaded.
    get_directory('rslts', sftp)

    # If requested, also download all intermediate results as well.
    if is_all:
        for candidate in sftp.listdir('.'):
            # Only directories are even potentially interesting.
            if not isdir(candidate, sftp):
github diffpy / diffpy.pdfgui / diffpy / pdfgui / control / connection.py View on Github external
port -- port of remote ssh service
        auth -- authenticate method, PSWDAUTH,RSAAUTH,DSAAUTH
        passwd --  only required if use PSWDAUTH
        keyFile -- only required if use RSAAUTH or DSAAUTH
        passphrase -- only required if use RSAAUTH or DSAAUTH, and passphrase is set
        """
        self.host = host
        self.user = user
        self.port = port
        self.auth = auth
        self.passwd = passwd
        self.keyFile = keyFile
        self.passphrase = passphrase

        try:
            transport = paramiko.Transport((self.host, self.port))
            transport.start_client()
            if auth == Connection.RSAAUTH:
                self.__rsa_auth(transport)
            elif auth == Connection.DSAAUTH:
                self.__dsa_auth(transport)
            else:
                # use password
                transport.auth_password(self.user, self.passwd)
                if not transport.is_authenticated():
                    raise ControlAuthError,\
                "Connection: '%s@%s' does not exist or password is wrong"%(self.user, self.host)
        except IOError:
            raise ControlFileError,\
            "Connection: can't open rsa/dsa file %s"%self.keyFile
        except (paramiko.SSHException, paramiko.BadAuthenticationType):
            raise ControlAuthError,\
github CityOfNewYork / NYCOpenRecords / app / lib / file_utils.py View on Github external
def sftp_ctx():
    """
    Context manager that provides an SFTP client object
    (an SFTP session across an open SSH Transport)
    """
    transport = paramiko.Transport((current_app.config['SFTP_HOSTNAME'],
                                    int(current_app.config['SFTP_PORT'])))
    transport.connect(username=current_app.config['SFTP_USERNAME'],
                      pkey=paramiko.RSAKey(filename=current_app.config['SFTP_RSA_KEY_FILE']))
    sftp = paramiko.SFTPClient.from_transport(transport)
    try:
        yield sftp
    except Exception as e:
        raise paramiko.SFTPError("Exception occurred with SFTP: {}".format(e))
    finally:
        sftp.close()
        transport.close()
github optixx / quickdev16 / scripts / query_romsize.py View on Github external
def main():

    port = 22
    password = getpass.getpass('Password for %s@%s: ' % (username, hostname))
    hostkeytype = None
    hostkey = None
    host_keys = paramiko.util.load_host_keys(
        os.path.expanduser('~/.ssh/known_hosts'))
    if host_keys.has_key(hostname):
        hostkeytype = host_keys[hostname].keys()[0]
        hostkey = host_keys[hostname][hostkeytype]
        print 'Using host key of type %s' % hostkeytype
    try:
        print "Connect %s:%s" % (hostname, port)
        t = paramiko.Transport((hostname, port))
        t.connect(username=username, password=password, hostkey=hostkey)
        sftp = paramiko.SFTPClient.from_transport(t)

        # dirlist on remote host
        dirlist = sftp.listdir('.')
        print "Dirlist:", dirlist

        conn = sqlite3.connect('roms_cleanup.sqlite3')
        c = conn.cursor()
        for i in [(1,), (2,), (4,), (8,), (16,)]:
            dirname = os.path.join(path, "%02i" % i)
            if not os.path.isdir(dirname):
                os.mkdir(dirname)
            print "#" * 60
            print "%i MBit" % i
            print "#" * 60
github apache / mina-sshd / sshd-sources / python / sftpclient.py View on Github external
sftp = None
    transport = None
    try:
        key = None
        if keyfile is not None:
            # Get private key used to authenticate user.
            if keytype == 'DSA':
                # The private key is a DSA type key.
                key = paramiko.DSSKey.from_private_key_file(keyfile)
            else:
                # The private key is a RSA type key.
                key = paramiko.RSAKey.from_private_key(keyfile)

        # Create Transport object using supplied method of authentication.
        transport = paramiko.Transport((host, port))
        transport.connect(None, username, password, key)
 
        sftp = paramiko.SFTPClient.from_transport(transport)
        return sftp
    except Exception as e:
        print('An error occurred creating SFTP client: %s: %s' % (e.__class__, e))

        if sftp is not None:
            try:
                sftp.close()
            except Exception as err:
                print('Failed to close SFTP client: %s: %s' % (err.__class__, err))

        if transport is not None:
            try:
                transport.close()
github fabioz / Pydev / make_release.py View on Github external
def UploadToFtp():
    '''
    Depends on paramiko: http://pypi.python.org/pypi/paramiko/1.7.2
    and PyCrypto: http://www.voidspace.org.uk/python/modules.shtml#pycrypto
    
    Examples from http://commandline.org.uk/python/sftp-python/
    '''
    import paramiko
    paramiko.util.log_to_file('/tmp/paramiko.log')
    host = "example.com"
    port = 22
    transport = paramiko.Transport((host, port))
    password = "example101"
    username = "warrior"
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    try:
        filepath = '/home/zeth/lenna.jpg'
        localpath = '/home/zeth/lenna.jpg'
        sftp.get(filepath, localpath)
        filepath = '/home/zeth/lenna.jpg'
        localpath = '/home/zeth/lenna.jpg'
        sftp.put(filepath, localpath)
    finally:
        sftp.close()
        transport.close()
github eppye-bots / bots / bots / communication.py View on Github external
hostkey = None
        if self.userscript and hasattr(self.userscript,'privatekey'):
            privatekeyfile,pkeytype,pkeypassword = botslib.runscript(self.userscript,self.scriptname,'privatekey',channeldict=self.channeldict)
            if pkeytype == 'RSA':
                pkey = paramiko.RSAKey.from_private_key_file(filename=privatekeyfile,password=pkeypassword)
            else:
                pkey = paramiko.DSSKey.from_private_key_file(filename=privatekeyfile,password=pkeypassword)
        else:
            pkey = None

        if self.channeldict['secret']:  #if password is empty string: use None. Else error can occur.
            secret = self.channeldict['secret']
        else:
            secret = None
        # now, connect and use paramiko Transport to negotiate SSH2 across the connection
        self.transport = paramiko.Transport((hostname,port))
        self.transport.connect(username=self.channeldict['username'],password=secret,hostkey=hostkey,pkey=pkey)
        self.session = paramiko.SFTPClient.from_transport(self.transport)
        channel = self.session.get_channel()
        channel.settimeout(botsglobal.ini.getint('settings','ftptimeout',10))
        self.set_cwd()
github zstackio / zstack-utility / zstacklib / zstacklib / utils / ssh.py View on Github external
def __init__(self, username, password, host, port=22):
        self.host = host
        self.transport = paramiko.Transport((host, port))
        self.transport.connect(username=username, password=password)
        self.sftp = paramiko.SFTPClient.from_transport(self.transport)