How to use the paramiko.SFTPClient.from_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 unbit / pysftpserver / pysftpserver / proxystorage.py View on Github external
except paramiko.SSHException as e:
                        print(
                            "Authentication with identity {}... failed".format(
                                pkey.get_base64()[:10]
                            )
                        )
                else:  # none of the keys worked
                    raise paramiko.SSHException
        except paramiko.SSHException:
            print(
                "None of the provided authentication methods worked. Exiting."
            )
            self.transport.close()
            sys.exit(1)

        self.client = paramiko.SFTPClient.from_transport(self.transport)

        # Let's retrieve the current dir
        self.client.chdir('.')
        self.home = self.client.getcwd()
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 salmonx / crawler_old / diedcmds / download_merge.py View on Github external
def download(path, fn):
    for ip in ips:
        ssh = paramiko.Transport((ip, 22))
        #ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(username=username,password=password)
        sftp = paramiko.SFTPClient.from_transport(ssh)
        out("################################  %s  ################################## " % ip)
        nf = ip + SEP + os.path.basename(fn)
        sftp.get(os.path.join(path, fn), nf)
        
        out("[OK] download: %s " %  nf)
        sftp.close()
github KopfKrieg / cloudzec / libcloudzec.py View on Github external
self.debug('  Use password login')
            try:
                self._transport.connect(username=self.remoteUsername, password=getpass.getpass('    Password for remote host: '))
            except paramiko.ssh_exception.BadAuthenticationType:
                self.debug('      Hm. Login with password doesn\'t work. Did you set „identFile“ in {}?'.format(self.confFile))
                raise Exception('Remote host doesn\'t accept passwords')
        else:
            self.debug('  Use identity file for login')
            key = None
            identFile = os.path.expanduser(self.identFile)
            try:
                key = paramiko.RSAKey.from_private_key_file(identFile)
            except paramiko.ssh_exception.PasswordRequiredException:
                key = paramiko.RSAKey.from_private_key_file(identFile, password=getpass.getpass('    Password for identity file: '))
            self._transport.connect(username=self.remoteUsername, pkey=key)
        self.sftp = paramiko.SFTPClient.from_transport(self._transport)
        self.debug('  Connected to remote host: {}@{}:{}'.format(self.remoteUsername, self.remoteHost, self.remotePort))
        # Check remotePath | Path like /home/$remoteUsername/cloudzec on the remote device!
        if self.remotePath is None:
            self.debug('  Create default remotePath')
            self.remotePath = os.path.join(self.sftp.normalize('.'), 'cloudzec')
            self.debug('    {}'.format(self.remotePath))
            self.storeConfiguration()
github onitu / onitu / drivers / sftp / onitu_sftp / sftp.py View on Github external
pkey_path, passphrase):
    """Helper function to connect with SFTP. Tries to connect with the given
    connection infos and, if successful, returns a SFTPClient ready to be
    used.
    Raises DriverError if an error occurred during the client setup."""
    transport = paramiko.Transport((hostname, port))
    try:
        if password != '':
            transport.connect(username=username, password=password)
        else:
            pkey_path = os.path.expanduser(pkey_path)
            privateKey = get_private_key(pkey_path, passphrase)
            transport.connect(username=username, pkey=privateKey)
    except SSHException as se:
        raise DriverError(u"Failed to connect to host: {}".format(se))
    sftpClient = paramiko.SFTPClient.from_transport(transport)
    return sftpClient
github unias / docklet / src / master / deploy.py View on Github external
def deploy(ipaddr,masterip,account,password,volumename):
    while True:
        try:
            transport = paramiko.Transport((ipaddr,22))
            transport.connect(username=account,password=password)
            break
        except Exception as e:
            time.sleep(2)
            pass
    sftp = paramiko.SFTPClient.from_transport(transport)

    currentfilepath = os.path.dirname(os.path.abspath(__file__))
    deployscriptpath = currentfilepath + "/../tools/docklet-deploy.sh"
    sftp.put(deployscriptpath,'/root/docklet-deploy.sh')
    sftp.put('/etc/hosts', '/etc/hosts')
    transport.close()
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    while True:
        try:
            ssh.connect(ipaddr, username = account, password = password, timeout = 300)
            break
        except Exception as e:
            time.sleep(2)
            pass
github leo-editor / leo-editor / leo / plugins / sftp.py View on Github external
'Unknown host: %s' % host,
                'Add the server key for host \'%s\' to the trusted host list?' % host)
            if store:
                self.set_hostkey(host, hostkey)
            else:
                return (None,None) # abort
        elif cached_hostkey != hostkey:
            store = self.confirm_hostkey(
                'Hostkey does not match!',
                'The remote host \'%s\' provided a key that does not match the stored key. ' +
                ' This could indicate a man-in-the-middle attack.  Continue anyway?' % host)
            if store:
                self.set_hostkey(host, hostkey)
            else:
                return (None,None) # abort
        sftp = paramiko.SFTPClient.from_transport(t)
        return (t,sftp)
    #@+node:peckj.20140218144401.6172: *3* commands
github gentoo / portage / lib / portage / getbinpkg.py View on Github external
else:
				sys.stderr.write(colorize("WARN",
					_(" * No password provided for username")) + " '%s'" % \
					(username,) + "\n\n")
				conn.login(username)
			conn.set_pasv(passive)
			conn.set_debuglevel(0)
		elif protocol == "sftp":
			try:
				import paramiko
			except ImportError:
				raise NotImplementedError(
					_("paramiko must be installed for sftp support"))
			t = paramiko.Transport(host)
			t.connect(username=username, password=password)
			conn = paramiko.SFTPClient.from_transport(t)
		else:
			raise NotImplementedError(_("%s is not a supported protocol.") % protocol)

	return (conn, protocol, address, http_params, http_headers)
github lvmgeo / GISPython / GISPython / SFTPHelper.py View on Github external
self.port = port
        self.username = userName
        self.password = password

        if not pkey_file is None:
            pkey = paramiko.RSAKey.from_private_key_file(pkey_file)

        # Transporta objekta izveide
        self.transport = paramiko.Transport((self.host, self.port))
        if pkey_file is None:
            self.transport.connect(username=self.username, password=self.password)
        else:
            self.transport.connect(username=self.username, pkey = pkey)

        # SFTP objekta izveide
        self.sftp = paramiko.SFTPClient.from_transport(self.transport)
github welliamcao / OpsManage / OpsManage / OpsManage / utils / ssh_tools.py View on Github external
def upload(self,localPath,remotePath):
        try:
            data = {}
            sftp = paramiko.SFTPClient.from_transport(self.ssh) 
            sftp.put(localPath,remotePath)
            data["ip"] = self.hostname
            data["status"] = 'success'
            data["msg"] = ""
            return data
        except Exception,e:
            data["ip"] = self.hostname
            data["status"] = 'failed'
            data["msg"] = str(e)
            return data