Python os.close() Examples

The following are 30 code examples for showing how to use os.close(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: ALF   Author: blackberry   File: _gdb.py    License: Apache License 2.0 7 votes vote down vote up
def _symbolize(target, output, tool, exp_opt):
    fd, tmp_log = tempfile.mkstemp(prefix="%s_log" % tool, suffix=".txt", dir=".")
    try:
        os.write(fd, output)
    finally:
        os.close(fd)
    try:
        result = _common.run([TOOL_GDB, "-batch", "-nx",
                                        "-ex", "set python print-stack full",
                                        "-ex", "py import exploitable",
                                        "-ex", "exploitable -m %s %s" % (exp_opt, tmp_log),
                                        "-ex", "quit", target], timeout=180)
    finally:
        _common.delete(tmp_log)
    if result.classification == _common.TIMEOUT:
        raise RuntimeError("Timed out while processing %s output:\n%s" % (tool, output))
    result.backtrace, result.classification = _process_gdb_output(result.text)
    result.text = _common._limit_output_length(result.text)
    if result.classification == _common.NOT_AN_EXCEPTION:
        raise RuntimeError("Failed to process %s output:\n%s" % (tool, output))
    return result 
Example 2
Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 6 votes vote down vote up
def whitelist_add():
    log.info("whitelist_add called")
    try:
        file_ = request.files["file"]
        handle, filename = tempfile.mkstemp()
        os.close(handle)
        file_.save(filename)
        data = request.get_json()
        if data and "functions" in data:
            functions = data["functions"]
        else:
            functions = None
        bass.whitelist_add(filename, functions)
        os.unlink(filename)
    except KeyError:
        log.exception("")
        return make_response(jsonify(message = "Sample file 'file' missing in POST request"), 400)

    return jsonify(message = "OK") 
Example 3
Project: XFLTReaT   Author: earthquake   File: packetselector.py    License: MIT License 6 votes vote down vote up
def replace_client(self, old_client, new_client):
		if old_client in self.clients:
			self.clients.remove(old_client)
			self.clients.append(new_client)
			try:
				old_client.get_pipe_w_fd().close()
			except:
				pass
			try:
				old_client.get_pipe_r_fd().close()
			except:
				pass
			try:
				socket.close(old_client.get_socket())
			except:
				pass

	# removing client from the client list 
Example 4
Project: WiCC   Author: pabloibiza   File: wicc_control.py    License: GNU General Public License v3.0 6 votes vote down vote up
def stop_running(self):
        """
        Stops the program execution. Notifies the view to finish itself, then deletes the reference.
        :return: none

        :Author: Miguel Yanes Fernández
        """
        try:
            self.stop_scan()
            self.semGeneral.release()
            self.view.reaper_calls()
            self.show_message("\n\n\tClossing WiCC ...\n\n")
            os.close(2)  # block writing to stderr
            del self.view
            self.running_stopped = True
            exit(0)
        except:
            raise SystemExit 
Example 5
Project: WiCC   Author: pabloibiza   File: wicc_control.py    License: GNU General Public License v3.0 6 votes vote down vote up
def open_cracked_passwords(self):
        """
        Opens the cracked passwords file.

        :author: Pablo Sanz Alguacil
        """

        try:
            self.show_message("Opening passwords file")
            passwords = self.local_folder + "/" + self.passwords_file_name
            open(passwords, 'r').close()  # just to raise an exception if the file doesn't exists
            command = ['xdg-open', passwords]
            thread = threading.Thread(target=self.execute_command, args=(command,))
            thread.start()
        except FileNotFoundError:
            self.show_warning_notification("No stored cracked networks. You need to do and finish an attack") 
Example 6
Project: Paradrop   Author: ParadropLabs   File: device.py    License: Apache License 2.0 6 votes vote down vote up
def update(ctx):
    """
    Update the chute from the working directory.
    """
    url = ctx.obj['chute_url']
    headers = {'Content-Type': 'application/x-tar'}

    if not os.path.exists("paradrop.yaml"):
        raise Exception("No paradrop.yaml file found in working directory.")

    with tempfile.TemporaryFile() as temp:
        tar = tarfile.open(fileobj=temp, mode="w")
        for dirName, subdirList, fileList in os.walk('.'):
            for fname in fileList:
                path = os.path.join(dirName, fname)
                arcname = os.path.normpath(path)
                tar.add(path, arcname=arcname)
        tar.close()

        temp.seek(0)
        res = router_request("PUT", url, headers=headers, data=temp)
        data = res.json()
        ctx.invoke(watch, change_id=data['change_id']) 
Example 7
Project: firmanal   Author: kyechou   File: extractor.py    License: MIT License 6 votes vote down vote up
def update_database(self, field, value):
        """
        Update a given field in the database.
        """
        ret = True
        if self.database:
            try:
                cur = self.database.cursor()
                cur.execute("UPDATE image SET " + field + "='" + value +
                            "' WHERE id=%s", (self.tag, ))
                self.database.commit()
            except BaseException:
                ret = False
                traceback.print_exc()
                self.database.rollback()
            finally:
                if cur:
                    cur.close()
        return ret 
Example 8
Project: rtp_cluster   Author: sippy   File: misc.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def daemonize(logfile = None):
    # Fork once
    if os.fork() != 0:
        os._exit(0)
    # Create new session
    os.setsid()
    if os.fork() != 0:
        os._exit(0)
    os.chdir('/')
    fd = os.open('/dev/null', os.O_RDWR)
    os.dup2(fd, sys.__stdin__.fileno())
    if logfile != None:
        fake_stdout = open(logfile, 'a', 1)
        sys.stdout = fake_stdout
        sys.stderr = fake_stdout
        fd = fake_stdout.fileno()
    os.dup2(fd, sys.__stdout__.fileno())
    os.dup2(fd, sys.__stderr__.fileno())
    if logfile == None:
        os.close(fd) 
Example 9
Project: jawfish   Author: war-and-code   File: tarfile.py    License: MIT License 6 votes vote down vote up
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
        """Open bzip2 compressed tar archive name for reading or writing.
           Appending is not allowed.
        """
        if len(mode) > 1 or mode not in "rw":
            raise ValueError("mode must be 'r' or 'w'.")

        try:
            import bz2
        except ImportError:
            raise CompressionError("bz2 module is not available")

        fileobj = bz2.BZ2File(fileobj or name, mode,
                              compresslevel=compresslevel)

        try:
            t = cls.taropen(name, mode, fileobj, **kwargs)
        except (IOError, EOFError):
            fileobj.close()
            raise ReadError("not a bzip2 file")
        t._extfileobj = False
        return t 
Example 10
Project: jawfish   Author: war-and-code   File: tarfile.py    License: MIT License 6 votes vote down vote up
def xzopen(cls, name, mode="r", fileobj=None, preset=None, **kwargs):
        """Open lzma compressed tar archive name for reading or writing.
           Appending is not allowed.
        """
        if mode not in ("r", "w"):
            raise ValueError("mode must be 'r' or 'w'")

        try:
            import lzma
        except ImportError:
            raise CompressionError("lzma module is not available")

        fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)

        try:
            t = cls.taropen(name, mode, fileobj, **kwargs)
        except (lzma.LZMAError, EOFError):
            fileobj.close()
            raise ReadError("not an lzma file")
        t._extfileobj = False
        return t

    # All *open() methods are registered here. 
Example 11
Project: S4   Author: MichaelAquilina   File: local.py    License: GNU General Public License v3.0 6 votes vote down vote up
def put(self, key, sync_object, callback=None):
        path = os.path.join(self.path, key)
        self.ensure_path(path)

        BUFFER_SIZE = 4096
        fd, temp_path = tempfile.mkstemp()

        try:
            with open(temp_path, "wb") as fp_1:
                while True:
                    data = sync_object.fp.read(BUFFER_SIZE)
                    fp_1.write(data)
                    if callback is not None:
                        callback(len(data))
                    if len(data) < BUFFER_SIZE:
                        break
            shutil.move(temp_path, path)
        except Exception:
            os.remove(temp_path)
            raise
        finally:
            os.close(fd)

        self.set_remote_timestamp(key, sync_object.timestamp) 
Example 12
Project: clikit   Author: sdispater   File: terminal.py    License: MIT License 5 votes vote down vote up
def _get_terminal_size_linux(self):
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios

                cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
                return cr
            except:
                pass

        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass

        if not cr:
            try:
                cr = (os.environ["LINES"], os.environ["COLUMNS"])
            except:
                return None

        return int(cr[1]), int(cr[0]) 
Example 13
Project: BASS   Author: Cisco-Talos   File: server.py    License: GNU General Public License v2.0 5 votes vote down vote up
def job_add_sample(job_id):
    try:
        samples = []
        for name, file_ in request.files.items():
            handle, filename = tempfile.mkstemp()
            os.close(handle)
            file_.save(filename)
            samples.append(bass.get_job(job_id).add_sample(filename, name))
        return jsonify(message = "ok", samples = [s.json() for s in samples])
    except KeyError:
        log.exception("Invalid job id")
        return make_response(jsonify(message = "Invalid job id"), 400) 
Example 14
Project: cherrypy   Author: cherrypy   File: test_wsgi_unix_socket.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def usocket_path():
    fd, path = tempfile.mkstemp('cp_test.sock')
    os.close(fd)
    os.remove(path)
    return path 
Example 15
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: pipes.py    License: MIT License 5 votes vote down vote up
def run(self):
    print("Attempting to pipein to pipe")
    self.pipein = os.fdopen(self.pipein, 'w')
    self.pipein.write("My Name is Elliot")
    self.pipein.close() 
Example 16
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: pipes.py    License: MIT License 5 votes vote down vote up
def main():
  pipeout, pipein = os.pipe()

  child = ChildProcess(pipein)
  child.start()
  child.join()

  os.close(pipein)
  pipeout = os.fdopen(pipeout)

  pipeContent = pipeout.read()
  print("Pipe: {}".format(pipeContent)) 
Example 17
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: exceptionHandling.py    License: MIT License 5 votes vote down vote up
def run(self):
    try:
      raise Exception("This broke stuff")
    except:
      except_type, except_class, tb = sys.exc_info()

      self.pipein = os.fdopen(self.pipein, 'w')
      self.pipein.write(str(tb))
      self.pipein.close() 
Example 18
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: exceptionHandling.py    License: MIT License 5 votes vote down vote up
def main():
  pipeout, pipein = os.pipe()

  childProcess = MyProcess(pipein)
  childProcess.start()
  childProcess.join()

  os.close(pipein)
  pipeout = os.fdopen(pipeout)

  pipeContent = pipeout.read()
  print("Exception: {}".format(pipeContent)) 
Example 19
Project: XFLTReaT   Author: earthquake   File: DNS.py    License: MIT License 5 votes vote down vote up
def cleanup(self):
		common.internal_print("Shutting down module: {0}".format(self.get_module_name()))
		#ugly hack to be removed later
		os.system("iptables -t mangle -F")
		try:
			self.comms_socket.close()
		except:
			pass
		try:
			os.close(self.tunnel)
		except:
			pass 
Example 20
Project: XFLTReaT   Author: earthquake   File: ICMP.py    License: MIT License 5 votes vote down vote up
def cleanup(self):
		common.internal_print("Shutting down module: {0}".format(self.get_module_name()))
		if self.serverorclient:
			if self.os_type == common.OS_LINUX:
				os.system("echo {0} > /proc/sys/net/ipv4/icmp_echo_ignore_all".format(self.orig_ieia_value)) #???
		try:
			self.comms_socket.close()
		except:
			pass
		try:
			os.close(self.tunnel)
		except:
			pass 
Example 21
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    License: MIT License 5 votes vote down vote up
def cleanup(self):
		common.internal_print("Shutting down module: {0}".format(self.get_module_name()))
		try:
			self.comms_socket.close()
		except:
			pass
		try:
			os.close(self.tunnel)
		except:
			pass 
Example 22
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 5 votes vote down vote up
def lin_close_tunnel(self, tun):
		try:
			os.close(tun)
		except:
			pass

		return 
Example 23
Project: XFLTReaT   Author: earthquake   File: interface.py    License: MIT License 5 votes vote down vote up
def mac_close_tunnel(self, tun):
		try:
			os.close(tun)
		except:
			pass

		return 
Example 24
Project: XFLTReaT   Author: earthquake   File: packetselector.py    License: MIT License 5 votes vote down vote up
def delete_client(self, client):
		if client in self.clients:

			if self.os_type == common.OS_WINDOWS:
				import win32file

				try:
					win32file.CloseHandle(client.get_pipe_r())
					win32file.CloseHandle(client.get_pipe_w())
				except Exception as e:
					common.internal_print("Remove authenticated client: CloseHandle exception: {0}".format(e), -1)
			else:
				try:
					client.get_pipe_r_fd().close()
					client.get_pipe_w_fd().close()
				except Exception as e:
					common.internal_print("Remove authenticated client: os.close exception: {0}".format(e), -1)

			client.call_stopfp()
			self.clients.remove(client)

		return

	# This function should run from the point when the framework was started.
	# It runs as an infinite loop to read the packets off the tunnel.
	# When an IPv4 packet was found that will be selected and checked whether
	# it addresses a client in the client list. If a client was found, then the
	# packet will be written on that pipe. 
Example 25
Project: WiCC   Author: pabloibiza   File: wicc_control.py    License: GNU General Public License v3.0 5 votes vote down vote up
def store_local_file(self, file_name, file_contents):
        """
        Stores the passed content in a local file (adds the content if it already exists)
        :param file_name: name of the file
        :param file_contents: contents to store on the file
        :return: none

        :Author: Miguel Yanes Fernández
        """
        if not self.ignore_local_savefiles:
            with open(self.local_folder + "/" + file_name, "a") as file:
                file.write(file_contents + "\n")
                file.close()
            chmod_cmd = ['chmod', '664', self.local_folder + "/" + file_name]
            self.execute_command(chmod_cmd) 
Example 26
Project: Paradrop   Author: ParadropLabs   File: pdmock.py    License: Apache License 2.0 5 votes vote down vote up
def writeTempFile(data):
    """
    Write data to a temporary file and return path to that file.
    """
    fd, path = tempfile.mkstemp()
    os.write(fd, data)
    os.close(fd)
    return path 
Example 27
Project: Paradrop   Author: ParadropLabs   File: test_pdosq.py    License: Apache License 2.0 5 votes vote down vote up
def test_read_yaml_file():
    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, "w") as output:
        output.write("value: 42\n")

    result = pdosq.read_yaml_file(path)
    assert result['value'] == 42

    pdosq.safe_remove(path)
    assert pdosq.read_yaml_file(path, default=None) is None
    assert pdosq.read_yaml_file(path, default={}) == {} 
Example 28
Project: Paradrop   Author: ParadropLabs   File: test_pdosq.py    License: Apache License 2.0 5 votes vote down vote up
def test_safe_remove():
    fd, path = tempfile.mkstemp()
    os.close(fd)

    # The first call should return True (file removed).
    assert pdosq.safe_remove(path) is True

    # The second call should return False (no file removed).
    assert pdosq.safe_remove(path) is False 
Example 29
Project: Paradrop   Author: ParadropLabs   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def open_text_editor(data):
    if data is None:
        data = ""

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        output.write(data)

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()

    # Check if the file has been modified, and if it has, send the update.
    new_mtime = os.path.getmtime(path)
    if new_mtime == orig_mtime:
        data = None

    os.remove(path)
    return data 
Example 30
Project: Paradrop   Author: ParadropLabs   File: util.py    License: Apache License 2.0 5 votes vote down vote up
def open_yaml_editor(data, description):
    if data is None:
        data = {}

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        if len(data) > 0:
            output.write(yaml.safe_dump(data, default_flow_style=False))
        output.write("\n")
        output.write("# You are editing the configuration for the {}.\n".format(description))
        output.write("# Blank lines and lines starting with '#' will be ignored.\n")
        output.write("# Save and exit to apply changes; exit without saving to discard.\n")

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()
        new_data = yaml.safe_load(data)

    # If result is null, convert to an empty dict before sending to router.
    if new_data is None:
        new_data = {}

    # Check if the file has been modified.
    new_mtime = os.path.getmtime(path)
    changed = (new_mtime != orig_mtime)

    os.remove(path)
    return new_data, changed