Upload file-ios to the specified host using SFTP. Supports uploading files
    with sudo by uploading to a temporary directory then moving & chowning.
335314
def put_file(
    state, host, filename_or_io, remote_filename,
    sudo=False, sudo_user=None, su_user=None, print_output=False,
):
    '''
    
    '''

    # sudo/su are a little more complicated, as you can only sftp with the SSH
    # user connected, so upload to tmp and copy/chown w/sudo and/or su_user
    if sudo or su_user:
        # Get temp file location
        temp_file = state.get_temp_filename(remote_filename)
        _put_file(host, filename_or_io, temp_file)

        if print_output:
            print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename))

        # Execute run_shell_command w/sudo and/or su_user
        command = 'mv {0} {1}'.format(temp_file, remote_filename)

        # Move it to the su_user if present
        if su_user:
            command = '{0} && chown {1} {2}'.format(command, su_user, remote_filename)

        # Otherwise any sudo_user
        elif sudo_user:
            command = '{0} && chown {1} {2}'.format(command, sudo_user, remote_filename)

        status, _, stderr = run_shell_command(
            state, host, command,
            sudo=sudo, sudo_user=sudo_user, su_user=su_user,
            print_output=print_output,
        )

        if status is False:
            logger.error('File error: {0}'.format('\n'.join(stderr)))
            return False

    # No sudo and no su_user, so just upload it!
    else:
        _put_file(host, filename_or_io, remote_filename)

        if print_output:
            print('{0}file uploaded: {1}'.format(host.print_prefix, remote_filename))

    return True
1131151
def upload_file(fapi, file_name, conf):
    
    if not conf.has_key('file-type'):
        raise SmarterlingError("%s doesn't have a file-type" % file_name)
    print("Uploading %s to smartling" % file_name)
    data = UploadData(
        os.path.dirname(file_name)+os.sep,
        os.path.basename(file_name),
        conf.get('file-type'))
    data.setUri(file_uri(file_name, conf))
    if conf.has_key('approve-content'):
        data.setApproveContent("true" if conf.get('approve-content', True) else "false")
    if conf.has_key('callback-url'):
        data.setCallbackUrl(conf.get('callback-url'))
    for name, value in conf.get('directives', {}).items():
        data.addDirective(SmartlingDirective(name, value))
    (response, code) = fapi.upload(data)
    if code!=200:
        print(repr(response))
        raise SmarterlingError("Error uploading file: %s" % file_name)
    else:
        print("Uploaded %s, wordCount: %s, stringCount: %s" % (file_name, response.data.wordCount, response.data.stringCount))
7716
def send_file(self, restricted=True, trusted=False, **kwargs):
        """"""
        return self.file.send_file(
            self.basename,
            restricted=restricted,
            mimetype=self.mimetype,
            trusted=trusted,
            **kwargs
        )
1067952
def upload(remote_location, remotes=None, ignores=None,
           static_root="/static/", prefix="", dry_run=False):
    # pylint:disable=too-many-arguments
    
    if remotes is None:
        remotes, ignores = _resources_files(
            abs_paths=remote_location.startswith('s3://'))
    if remote_location.startswith('s3://'):
        from deployutils.s3 import S3Backend
        backend = S3Backend(remote_location,
            static_root=static_root, dry_run=dry_run)
        backend.upload(list_local(remotes, prefix), prefix)
    else:
        excludes = []
        if ignores:
            for ignore in ignores:
                excludes += ['--exclude', ignore]
        # -O omit to set mod times on directories to avoid permissions error.
        shell_command(['/usr/bin/rsync']
            + excludes + ['-pOthrRvz', '--rsync-path', '/usr/bin/rsync']
            + remotes + [remote_location], dry_run=dry_run)
222025
def request(method, path, params, options)
      uri = options[:host] || @host
      uri = URI(uri) unless uri.respond_to?(:host)
      uri += path
      request_headers = {}
      if self.credentials?
        # When posting a file, don't sign any params
        # signature_params = if [:post, :put].include?(method.to_sym) && params.values.any?{|value| value.is_a?(File) || (value.is_a?(Hash) && (value[:io].is_a?(IO) || value[:io].is_a?(StringIO)))}
        #   {}
        # else
        #   params
        # end
        # authorization = SimpleOAuth::Header.new(method, uri, signature_params, credentials)
        # request_headers[:authorization] = authorization.to_s
        connection.basic_auth(credentials[:user], credentials[:password])
      end
      connection.url_prefix = options[:host] || @host
      connection.run_request(method.to_sym, path, nil, request_headers) do |request|
        unless params.empty?
          case request.method
          when :post, :put
            request.body = params
          else
            request.params.update(params)
          end
        end
        yield request if block_given?
      end.env
    rescue Faraday::Error::ClientError
      raise VulnDBHQ::Error::ClientError
    end
316260
def upload_settings():
    ""
    local_path = os.path.join(curdir, 'settings/{0}.py'.format(env.host))
    if os.path.exists(local_path):
        remote_path = os.path.join(env.path, 'varify/conf/local_settings.py')
        put(local_path, remote_path)
    elif not confirm(yellow('No local settings found for host "{0}". Continue anyway?'.format(env.host))):
        abort('No local settings found for host "{0}". Aborting.'.format(env.host))
818689
def add_fileobj(self, fname, fcontent):
        
        tar_info = tarfile.TarInfo(fname)
        if isinstance(fcontent, io.BytesIO):
            tar_info.size = len(fcontent.getvalue())
        elif isinstance(fcontent, io.StringIO):
            tar_info.size = len(fcontent.getvalue())
            fcontent = io.BytesIO(fcontent.getvalue().encode("utf8"))
        else:
            if hasattr(fcontent, "readable"):
                fcontent = fcontent
            tar_info.size = len(fcontent)
            if isinstance(fcontent, str):
                fcontent = fcontent.encode("utf8")
            fcontent = io.BytesIO(fcontent)
        self._ios_to_add[tar_info] = fcontent
605931
def put_file(self, in_path, out_path):
        '''  '''
        vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
        cmd = self._password_cmd()

        if C.DEFAULT_SCP_IF_SSH:
            cmd += ["scp"] + self.common_args
            cmd += [in_path,self.host + ":" + out_path]
            indata = None
        else:
            cmd += ["sftp"] + self.common_args + [self.host]
            indata = "put %s %s\n" % (in_path, out_path)

        p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self._send_password()
        stdout, stderr = p.communicate(indata)

        if p.returncode != 0:
            raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
32471
def upload(path, body, options={})
      options[:client_modified] = Time.now.utc.iso8601
      options[:path] = path
      resp = upload_request('/files/upload', body, options.merge(path: path))
      FileMetadata.new(resp)
    end
1119221
def scp_file(dest_path, contents=None, kwargs=None, local_file=None):
    '''
    
    '''
    file_to_upload = None
    try:
        if contents is not None:
            try:
                tmpfd, file_to_upload = tempfile.mkstemp()
                os.write(tmpfd, contents)
            finally:
                try:
                    os.close(tmpfd)
                except OSError as exc:
                    if exc.errno != errno.EBADF:
                        raise exc

        log.debug('Uploading %s to %s', dest_path, kwargs['hostname'])

        ssh_args = [
            # Don't add new hosts to the host key database
            '-oStrictHostKeyChecking=no',
            # Set hosts key database path to /dev/null, i.e., non-existing
            '-oUserKnownHostsFile=/dev/null',
            # Don't re-use the SSH connection. Less failures.
            '-oControlPath=none'
        ]

        if local_file is not None:
            file_to_upload = local_file
            if os.path.isdir(local_file):
                ssh_args.append('-r')

        if 'key_filename' in kwargs:
            # There should never be both a password and an ssh key passed in, so
            ssh_args.extend([
                # tell SSH to skip password authentication
                '-oPasswordAuthentication=no',
                '-oChallengeResponseAuthentication=no',
                # Make sure public key authentication is enabled
                '-oPubkeyAuthentication=yes',
                # do only use the provided identity file
                '-oIdentitiesOnly=yes',
                # No Keyboard interaction!
                '-oKbdInteractiveAuthentication=no',
                # Also, specify the location of the key file
                '-i {0}'.format(kwargs['key_filename'])
            ])

        if 'port' in kwargs:
            ssh_args.append('-oPort={0}'.format(kwargs['port']))

        ssh_args.append(__ssh_gateway_arguments(kwargs))

        try:
            if socket.inet_pton(socket.AF_INET6, kwargs['hostname']):
                ipaddr = '[{0}]'.format(kwargs['hostname'])
            else:
                ipaddr = kwargs['hostname']
        except socket.error:
            ipaddr = kwargs['hostname']

        if file_to_upload is None:
            log.warning(
                'No source file to upload. Please make sure that either file '
                'contents or the path to a local file are provided.'
            )
        cmd = (
            'scp {0} {1} {2[username]}@{4}:{3} || '
            'echo "put {1} {3}" | sftp {0} {2[username]}@{4} || '
            'rsync -avz -e "ssh {0}" {1} {2[username]}@{2[hostname]}:{3}'.format(
                ' '.join(ssh_args), file_to_upload, kwargs, dest_path, ipaddr
            )
        )

        log.debug('SCP command: \'%s\'', cmd)
        retcode = _exec_ssh_cmd(cmd,
                                error_msg='Failed to upload file \'{0}\': {1}\n{2}',
                                password_retries=3,
                                **kwargs)
    finally:
        if contents is not None:
            try:
                os.remove(file_to_upload)
            except OSError as exc:
                if exc.errno != errno.ENOENT:
                    raise exc
    return retcode
640676
function sftpPut(inFilename, cb) {
    var fromFile, toFile, from, to;

    fromFile = localRoot + localSep + inFilename;
    toFile = remoteRoot + remoteSep + inFilename.split(localSep).join(remoteSep);

    if(localSep != remoteSep) {
      toFile = toFile.replace(new RegExp(localSep == '\\' ? '\\\\' : '\\/', 'g'), remoteSep);
    }

    grunt.verbose.write(fromFile + ' to ' + toFile);

    var f_size = fs.statSync(fromFile).size;

    var upload = function(fromFile, toFile, cb) {
      sftpConn.fastPut( fromFile, toFile, function(err){
        if (err){
          log.write((' Error uploading file: ' + err.message).red + '\n');
          cb(err);
        } else {
          grunt.verbose.write(' done'.green + '\n' );
          if( with_progress ) progressLogger.tick();
          transferred += parseInt(f_size/1024);
          cb(null);
        }
      });
    };

    if (cacheEnabled) {
      fs.stat(fromFile, function(err, fromFileData){
        if (cache[fromFile] && +new Date(cache[fromFile]) >= +new Date(fromFileData.mtime)) {
          cb(null);
        } else {
          cache[fromFile] = fromFileData.mtime;
          upload(fromFile, toFile, cb);
        }
      } );
    } else {
      upload(fromFile, toFile, cb);
    }

  }
872981
function uploadFile(file, next) {
    var uploadErr;

    self.uploadFile({
      source: file.source,
      target: file.target,
      server: options.server,
      keys: options.keys,
      tunnel: options.tunnel,
      remoteUser: options.remoteUser
    }).on('error', function (err) {
      if (!uploadErr) {
        uploadErr = true;
        next(err);
      }
    }).on('complete', function () {
      if (!uploadErr) {
        next();
      }
    });
  }
230303
def upload_as_text(name, filename):
    
    location = list(IPList.objects.filter(name))
    if location:
        iplist = location[0]
        return iplist.upload(filename=filename, as_type='txt')
939589
def put(
    state, host, local_filename, remote_filename,
    user=None, group=None, mode=None, add_deploy_dir=True,
):
    '''
    
    '''

    # Upload IO objects as-is
    if hasattr(local_filename, 'read'):
        local_file = local_filename

    # Assume string filename
    else:
        # Add deploy directory?
        if add_deploy_dir and state.deploy_dir:
            local_filename = path.join(state.deploy_dir, local_filename)

        local_file = local_filename

        if not path.isfile(local_file):
            raise IOError('No such file: {0}'.format(local_file))

    mode = ensure_mode_int(mode)
    remote_file = host.fact.file(remote_filename)

    # No remote file, always upload and user/group/mode if supplied
    if not remote_file:
        yield (local_file, remote_filename)

        if user or group:
            yield chown(remote_filename, user, group)

        if mode:
            yield chmod(remote_filename, mode)

    # File exists, check sum and check user/group/mode if supplied
    else:
        local_sum = get_file_sha1(local_filename)
        remote_sum = host.fact.sha1_file(remote_filename)

        # Check sha1sum, upload if needed
        if local_sum != remote_sum:
            yield (local_file, remote_filename)

            if user or group:
                yield chown(remote_filename, user, group)

            if mode:
                yield chmod(remote_filename, mode)

        else:
            # Check mode
            if mode and remote_file['mode'] != mode:
                yield chmod(remote_filename, mode)

            # Check user/group
            if (
                (user and remote_file['user'] != user)
                or (group and remote_file['group'] != group)
            ):
                yield chown(remote_filename, user, group)
927311
def upload_file(f):
    
    with FilesOpener(f) as files:
        response = requests.post(
            'https://telegra.ph/upload',
            files=files
        ).json()

    if isinstance(response, list):
        error = response[0].get('error')
    else:
        error = response.get('error')

    if error:
        raise TelegraphException(error)

    return [i['src'] for i in response]
299703
def upload(self, localpath, href):
        
        localpath = _(localpath)
        href = remote(href)
        if not os.path.exists(localpath):
            logger.info(u("ERROR: localfile: %s not found") % localpath)
            return
        if os.path.islink(localpath):
            return self.upload(os.path.abspath(os.path.realpath(localpath)), href)
            # 3 tryings to upload file
        for iTry in range(TRYINGS):
            try:
                logger.info(u("upload: %s %s") % (localpath, href))
                length = os.path.getsize(localpath)

                if PY3:
                    _open = open(_encode_utf8(localpath), "r", encoding='latin-1')
                else:
                    _open = open(_encode_utf8(localpath), "r")
                with _open as f:
                    return self.write(f, href, length=length)
            except ConnectionException:
                raise
            except Exception:
                e = sys.exc_info()[1]
                logger.exception(e)
100245
def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None,
                                        content_type='application/octet-stream', auto_open=False,
                                        prevent_share=False, scope='content/send'):
        
        if input_file_path:
            with open(input_file_path, 'rb') as f:
                data = f.read()

        if not data:
            raise ValueError('Either the data of a file or the path to a file must be provided')

        params = {
            'fileName': file_name,
            'userId': user_id,
            'autoOpen': 'true' if auto_open else 'false',
            'preventShare': 'true' if prevent_share else 'false',
        }

        return _post(
            token=self.oauth.get_app_token(scope),
            uri='/user/media/file/send?' + urllib.urlencode(params),
            data=data,
            content_type=content_type
        )