コード例 #1
0
    def _copy_module(self, conn, tmp, module):
        ''' transfer a module over SFTP, does not run it '''

        if module.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" % module)

        # Search module path(s) for named module.
        for module_path in self.module_path.split(os.pathsep):
            in_path = os.path.expanduser(os.path.join(module_path, module))
            if os.path.exists(in_path):
                break
        else:
            raise errors.AnsibleFileNotFound("module %s not found in %s" %
                                             (module, self.module_path))

        out_path = os.path.join(tmp, module)

        # use the correct python interpreter for the host
        host_variables = self.inventory.get_variables(conn.host)
        if 'ansible_python_interpreter' in host_variables:
            interpreter = host_variables['ansible_python_interpreter']
            with open(in_path) as f:
                module_lines = f.readlines()
            if '#!' and 'python' in module_lines[0]:
                module_lines[0] = "#!%s" % interpreter
            self._transfer_str(conn, tmp, module, '\n'.join(module_lines))
        else:
            conn.put_file(in_path, out_path)

        return out_path
コード例 #2
0
ファイル: __init__.py プロジェクト: map7/ansible
    def _copy_module(self, conn, tmp, module_name, module_args, inject, complex_args=None):
        ''' transfer a module over SFTP, does not run it '''

        # FIXME if complex args is none, set to {}

        if module_name.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" % module_name)

        # Search module path(s) for named module.
        in_path = utils.plugins.module_finder.find_plugin(module_name)
        if in_path is None:
            raise errors.AnsibleFileNotFound("module %s not found in %s" % (module_name, utils.plugins.module_finder.print_paths()))

        out_path = os.path.join(tmp, module_name)

        module_data = ""
        module_style = 'old'

        with open(in_path) as f:
            module_data = f.read()
            if module_common.REPLACER in module_data:
                module_style = 'new'
            if 'WANT_JSON' in module_data:
                module_style = 'non_native_want_json'

            complex_args_json = utils.jsonify(complex_args)
            # We force conversion of module_args to str because module_common calls shlex.split,
            # a standard library function that incorrectly handles Unicode input before Python 2.7.3.
            encoded_args = repr(str(module_args))
            encoded_lang = repr(C.DEFAULT_MODULE_LANG)
            encoded_complex = repr(complex_args_json)

            module_data = module_data.replace(module_common.REPLACER, module_common.MODULE_COMMON)
            module_data = module_data.replace(module_common.REPLACER_ARGS, encoded_args)
            module_data = module_data.replace(module_common.REPLACER_LANG, encoded_lang)
            module_data = module_data.replace(module_common.REPLACER_COMPLEX, encoded_complex)

            if module_style == 'new':
                facility = C.DEFAULT_SYSLOG_FACILITY
                if 'ansible_syslog_facility' in inject:
                    facility = inject['ansible_syslog_facility']
                module_data = module_data.replace('syslog.LOG_USER', "syslog.%s" % facility)

        lines = module_data.split("\n")
        shebang = None
        if lines[0].startswith("#!"):
            shebang = lines[0].strip()
            args = shlex.split(str(shebang[2:]))
            interpreter = args[0]
            interpreter_config = 'ansible_%s_interpreter' % os.path.basename(interpreter)

            if interpreter_config in inject:
                lines[0] = shebang = "#!%s %s" % (inject[interpreter_config], " ".join(args[1:]))
                module_data = "\n".join(lines)

        self._transfer_str(conn, tmp, module_name, module_data)

        return (out_path, module_style, shebang)
コード例 #3
0
ファイル: __init__.py プロジェクト: jonnydubowsky/ansible
    def _copy_module(self, conn, tmp, module_name, module_args, inject):
        ''' transfer a module over SFTP, does not run it '''

        if module_name.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" %
                                             module_name)

        # Search module path(s) for named module.
        in_path = utils.plugins.module_finder.find_plugin(module_name)
        if in_path is None:
            raise errors.AnsibleFileNotFound(
                "module %s not found in %s" %
                (module_name, utils.plugins.module_finder.print_paths()))

        out_path = os.path.join(tmp, module_name)

        module_data = ""
        is_new_style = False

        with open(in_path) as f:
            module_data = f.read()
            if module_common.REPLACER in module_data:
                is_new_style = True
            module_data = module_data.replace(module_common.REPLACER,
                                              module_common.MODULE_COMMON)
            encoded_args = "\"\"\"%s\"\"\"" % module_args.replace("\"", "\\\"")
            module_data = module_data.replace(module_common.REPLACER_ARGS,
                                              encoded_args)
            encoded_lang = "\"\"\"%s\"\"\"" % C.DEFAULT_MODULE_LANG
            module_data = module_data.replace(module_common.REPLACER_LANG,
                                              encoded_lang)
            if is_new_style:
                facility = C.DEFAULT_SYSLOG_FACILITY
                if 'ansible_syslog_facility' in inject:
                    facility = inject['ansible_syslog_facility']
                module_data = module_data.replace('syslog.LOG_USER',
                                                  "syslog.%s" % facility)

        lines = module_data.split("\n")
        shebang = None
        if lines[0].startswith("#!"):
            shebang = lines[0]
            args = shlex.split(str(shebang[2:]))
            interpreter = args[0]
            interpreter_config = 'ansible_%s_interpreter' % os.path.basename(
                interpreter)

            if interpreter_config in inject:
                lines[0] = shebang = "#!%s %s" % (inject[interpreter_config],
                                                  " ".join(args[1:]))
                module_data = "\n".join(lines)

        self._transfer_str(conn, tmp, module_name, module_data)

        return (out_path, is_new_style, shebang)
コード例 #4
0
    def _copy_module(self, conn, tmp, module_name, module_args, inject):
        ''' transfer a module over SFTP, does not run it '''

        if module_name.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" %
                                             module_name)

        # Search module path(s) for named module.
        for module_path in self.module_path.split(os.pathsep):
            in_path = os.path.expanduser(os.path.join(module_path,
                                                      module_name))
            if os.path.exists(in_path):
                break
        else:
            raise errors.AnsibleFileNotFound("module %s not found in %s" %
                                             (module_name, self.module_path))

        out_path = os.path.join(tmp, module_name)

        module_data = ""
        is_new_style = False

        with open(in_path) as f:
            module_data = f.read()
            if module_common.REPLACER in module_data:
                is_new_style = True
            module_data = module_data.replace(module_common.REPLACER,
                                              module_common.MODULE_COMMON)
            encoded_args = "\"\"\"%s\"\"\"" % module_args.replace("\"", "\\\"")
            module_data = module_data.replace(module_common.REPLACER_ARGS,
                                              encoded_args)
            if is_new_style:
                facility = C.DEFAULT_SYSLOG_FACILITY
                if 'ansible_syslog_facility' in inject:
                    facility = inject['ansible_syslog_facility']
                module_data = module_data.replace('syslog.LOG_USER',
                                                  "syslog.%s" % facility)

        # use the correct python interpreter for the host
        if 'ansible_python_interpreter' in inject:
            interpreter = inject['ansible_python_interpreter']
            module_lines = module_data.split('\n')
            if '#!' and 'python' in module_lines[0]:
                module_lines[0] = "#!%s" % interpreter
            module_data = "\n".join(module_lines)

        self._transfer_str(conn, tmp, module_name, module_data)

        lines = module_data.split("\n")
        shebang = None
        if lines[0].startswith("#!"):
            shebang = lines[0]

        return (out_path, is_new_style, shebang)
コード例 #5
0
    def _copy_module(self, conn, tmp, module):
        ''' transfer a module over SFTP, does not run it '''

        if module.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" % module)
        in_path = os.path.expanduser(os.path.join(self.module_path, module))
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound("module not found: %s" % in_path)

        out_path = os.path.join(tmp, module)
        conn.put_file(in_path, out_path)
        return out_path
コード例 #6
0
    def _copy_module(self, conn, tmp, module):
        ''' transfer a module over SFTP, does not run it '''

        if module.startswith("/"):
            raise errors.AnsibleFileNotFound("%s is not a module" % module)

        # Search module path(s) for named module.
        for module_path in self.module_path.split(os.pathsep):
            in_path = os.path.expanduser(os.path.join(module_path, module))
            if os.path.exists(in_path):
                break
        else:
            raise errors.AnsibleFileNotFound("module %s not found in %s" % (module, self.module_path))
コード例 #7
0
    def fetch_file(self, in_path, out_path):
        ''' fetch a file from VM to local '''

        if not in_path.startswith(os.path.sep):
            in_path = os.path.join(os.path.sep, in_path)
        normpath = os.path.normpath(in_path)
        in_path = os.path.join("/", normpath[1:])

        vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
        f = pipes.quote(in_path)
        cmd = self.produce_command("test -f %s && cat %s || exit 7" % (f, f))
        try:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            out, err = p.communicate("")
            retval = p.wait()
            if retval == 7:
                raise errors.AnsibleFileNotFound(
                    "file or module does not exist: %s" % in_path)
            elif retval != 0:
                raise subprocess.CalledProcessError(retval, cmd)
            file(out_path, "wb").write(out)
        except subprocess.CalledProcessError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" %
                                      out_path)
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" %
                                      out_path)
コード例 #8
0
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to VM '''

        if not out_path.startswith(os.path.sep):
            out_path = os.path.join(os.path.sep, out_path)
        normpath = os.path.normpath(out_path)
        out_path = os.path.join("/", normpath[1:])

        vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound(
                "file or module does not exist: %s" % in_path)
        cmd = self.produce_command("cat > %s" % pipes.quote(out_path))
        try:
            p = subprocess.Popen(
                cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
            )
            out, _ = p.communicate(file(in_path).read())
            retval = p.wait()
            if retval != 0:
                raise QubesRPCError(retval, cmd, out)
        except subprocess.CalledProcessError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" %
                                      out_path)
コード例 #9
0
ファイル: ssh.py プロジェクト: cbrumgard/ansible
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to remote '''
        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))
コード例 #10
0
ファイル: __init__.py プロジェクト: afei418/ansible
    def _copy_module(self,
                     conn,
                     tmp,
                     module_name,
                     module_args,
                     inject,
                     complex_args=None):
        ''' transfer a module over SFTP, does not run it '''

        # Search module path(s) for named module.
        in_path = utils.plugins.module_finder.find_plugin(module_name)
        if in_path is None:
            raise errors.AnsibleFileNotFound(
                "module %s not found in %s" %
                (module_name, utils.plugins.module_finder.print_paths()))
        out_path = os.path.join(tmp, module_name)

        # insert shared code and arguments into the module
        (module_data, module_style,
         shebang) = module_replacer.modify_module(in_path, complex_args,
                                                  module_args, inject)

        # ship the module
        self._transfer_str(conn, tmp, module_name, module_data)
        return (out_path, module_style, shebang)
コード例 #11
0
 def put_file(self, in_path, out_path):
     display.vvv("execnet put_file %r %r" % (in_path, out_path))
     if not os.path.exists(in_path):
         raise errors.AnsibleFileNotFound(
             "file or module does not exist: %s" % in_path)
     with open(in_path) as f:
         self.rpc.put_file(f.read(), out_path)
コード例 #12
0
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to lxc '''
        super(Connection, self).put_file(in_path, out_path)
        self._display.vvv("PUT %s TO %s" % (in_path, out_path),
                          host=self.container_name)
        in_path = to_bytes(in_path, errors='surrogate_or_strict')
        out_path = to_bytes(out_path, errors='surrogate_or_strict')

        if not os.path.exists(in_path):
            msg = "file or module does not exist: %s" % in_path
            raise errors.AnsibleFileNotFound(msg)
        try:
            src_file = open(in_path, "rb")
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to open input file to %s" %
                                      in_path)
        try:

            def write_file(args):
                with open(out_path, 'wb+') as dst_file:
                    shutil.copyfileobj(src_file, dst_file)

            try:
                self.container.attach_wait(write_file, None)
            except IOError:
                traceback.print_exc()
                msg = "failed to transfer file to %s" % out_path
                raise errors.AnsibleError(msg)
        finally:
            src_file.close()
コード例 #13
0
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to remote '''
        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()

        host = self.host
        if self.ipv6:
            host = '[%s]' % host

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

        (p, stdin) = self._run(cmd, indata)

        self._send_password()

        com = self.CommunicateCallbacks(self.runner, indata)
        returncode = self._communicate(p, stdin, callbacks=(com.stdin_cb, com.stdout_cb, com.stderr_cb))

        if returncode != 0:
            raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, com.stdout, com.stderr))
コード例 #14
0
ファイル: paramiko_alt.py プロジェクト: threatgrid/ansible
 def put_file(self, in_path, out_path):
     ''' transfer a file from local to remote '''
     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)
     try:
         self.sftp = self.ssh.open_sftp()
     except Exception, e:
         raise errors.AnsibleError("failed to open a SFTP connection (%s)" % e)
コード例 #15
0
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to remote '''
        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)

        fd = file(in_path, 'rb')
        fstat = os.stat(in_path)
        try:
            vvv("PUT file is %d bytes" % fstat.st_size)
            last = False
            while fd.tell() <= fstat.st_size and not last:
                vvvv("file position currently %ld, file size is %ld" %
                     (fd.tell(), fstat.st_size))
                data = fd.read(CHUNK_SIZE)
                if fd.tell() >= fstat.st_size:
                    last = True
                data = dict(mode='put',
                            data=base64.b64encode(data),
                            out_path=out_path,
                            last=last)
                if self.runner.sudo:
                    data['user'] = self.runner.sudo_user
                data = utils.jsonify(data)
                data = utils.encrypt(self.key, data)

                if self.send_data(data):
                    raise errors.AnsibleError("failed to send the file to %s" %
                                              self.host)

                response = self.recv_data()
                if not response:
                    raise errors.AnsibleError(
                        "Failed to get a response from %s" % self.host)
                response = utils.decrypt(self.key, response)
                response = utils.parse_json(response)

                if response.get('failed', False):
                    raise errors.AnsibleError(
                        "failed to put the file in the requested location")
        finally:
            fd.close()
            vvvv("waiting for final response after PUT")
            response = self.recv_data()
            if not response:
                raise errors.AnsibleError("Failed to get a response from %s" %
                                          self.host)
            response = utils.decrypt(self.key, response)
            response = utils.parse_json(response)

            if response.get('failed', False):
                raise errors.AnsibleError(
                    "failed to put the file in the requested location")
コード例 #16
0
 def _copy_file(self, in_path, out_path):
     if not os.path.exists(in_path):
         raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
     try:
         shutil.copyfile(in_path, out_path)
     except shutil.Error:
         traceback.print_exc()
         raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
     except IOError:
         traceback.print_exc()
         raise errors.AnsibleError("failed to transfer file to %s" % out_path)
コード例 #17
0
ファイル: connection.py プロジェクト: mjvaldez/ansible
 def put_file(self, in_path, out_path):
     ''' transfer a file from local to remote '''
     if not os.path.exists(in_path):
         raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
     sftp = self.ssh.open_sftp()
     try:
         sftp.put(in_path, out_path)
     except IOError:
         traceback.print_exc()
         raise errors.AnsibleError("failed to transfer file to %s" % out_path)
     sftp.close()
コード例 #18
0
 def put_file(self, in_path, out_path):
     ''' transfer a file from local to local '''
     out_path = os.path.join(self.chroot, out_path.lstrip('/'))
     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)
     try:
         self._exec_command('cp {} {}'.format(in_path, out_path))
     except Exception:
         traceback.print_exc()
         raise errors.AnsibleError("Some exceptions occurred.")
コード例 #19
0
 def fetch_file(self, in_path, out_path):
     ''' fetch a file from local to local -- for copatibility '''
     in_path = os.path.join(self.chroot, in_path.lstrip('/'))
     vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
     if not os.path.exists(out_path):
         raise errors.AnsibleFileNotFound(
             "file or module does not exist: %s" % out_path)
     try:
         self._exec_command('cp {} {}'.format(in_path, out_path))
     except Exception:
         traceback.print_exc()
         raise errors.AnsibleError("Some exceptions occurred.")
コード例 #20
0
ファイル: local.py プロジェクト: yanc0/ansible
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to local '''

        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)
        try:
            shutil.copyfile(in_path, out_path)
        except shutil.Error:
            traceback.print_exc()
            raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" % out_path)
コード例 #21
0
    def _transfer_file(self, in_path, out_path):
        """ transfer a file from local to local """
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound(
                'file or modules does not exist: %s' % in_path)

        try:
            shutil.copyfile(in_path, out_path)
        except shutil.Error:
            raise errors.AnsibleError(
                'failed to copy: %s and %s are the same' % (in_path, outpath))
        except IOError:
            raise errors.AnsibleError('failed to transfer file to %s' %
                                      out_path)
コード例 #22
0
ファイル: ssh.py プロジェクト: ucxdvd/n-repo
 def put_file(self, in_path, out_path):
     ''' transfer a file from local to remote '''
     if not os.path.exists(in_path):
         raise errors.AnsibleFileNotFound(
             "file or module does not exist: %s" % in_path)
     sftp_cmd = ["sftp"] + self.common_args + [self.host]
     p = subprocess.Popen(sftp_cmd,
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE)
     stdout, stderr = p.communicate("put %s %s\n" % (in_path, out_path))
     if p.returncode != 0:
         raise errors.AnsibleError(
             "failed to transfer file to %s:\n%s\n%s" %
             (out_path, stdout, stderr))
コード例 #23
0
    def parse_hosts(cls, host_list, override_hosts=None, extra_vars=None):
        ''' parse the host inventory file, returns (hosts, groups) '''

        if override_hosts is None:
            inventory = ansible.inventory.Inventory(host_list, extra_vars)
        if type(host_list) == list:
            raise Exception("function can only be called on inventory files")

        host_list = os.path.expanduser(host_list)
        if not os.path.exists(host_list):
            raise errors.AnsibleFileNotFound("inventory file not found: %s" % host_list)

        if not os.access(host_list, os.X_OK):
            return Runner.parse_hosts_from_regular_file(host_list)
        else:
            return Runner.parse_hosts_from_script(host_list, extra_vars)
コード例 #24
0
    def put_file(self, in_path, out_path):
        """ Transfer a file from local to container """
        args = [self.docker_cmd, "exec", "-i", self.host, "bash", "-c",
                "cat > %s" % format(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)
        p = subprocess.Popen(args, stdin=open(in_path),
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.communicate()

        # HACK: Due to a race condition, this sometimes returns before
        # the file has been written to disk, so we sleep for one second
        time.sleep(1)
コード例 #25
0
ファイル: fireball.py プロジェクト: sshadmin/ansible
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to remote '''
        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)
        data = file(in_path).read()

        data = dict(mode='put', data=data, out_path=out_path)
        data = utils.jsonify(data)
        data = utils.encrypt(self.key, data)
        self.socket.send(data)

        response = self.socket.recv()
        response = utils.decrypt(self.key, response)
        response = utils.parse_json(response)
コード例 #26
0
ファイル: winrm.py プロジェクト: Devopst03/devopst
 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)
     with open(in_path) as in_file:
         in_size = os.path.getsize(in_path)
         script_template = '''
             $s = [System.IO.File]::OpenWrite("%s");
             [void]$s.Seek(%d, [System.IO.SeekOrigin]::Begin);
             $b = [System.Convert]::FromBase64String("%s");
             [void]$s.Write($b, 0, $b.length);
             [void]$s.SetLength(%d);
             [void]$s.Close();
         '''
         # Determine max size of data we can pass per command.
         script = script_template % (powershell._escape(out_path), in_size,
                                     '', in_size)
         cmd = powershell._encode_script(script)
         # Encode script with no data, subtract its length from 8190 (max
         # windows command length), divide by 2.67 (UTF16LE base64 command
         # encoding), then by 1.35 again (data base64 encoding).
         buffer_size = int(((8190 - len(cmd)) / 2.67) / 1.35)
         for offset in xrange(0, in_size, buffer_size):
             try:
                 out_data = in_file.read(buffer_size)
                 if offset == 0:
                     if out_data.lower().startswith(
                             '#!powershell'
                     ) and not out_path.lower().endswith('.ps1'):
                         out_path = out_path + '.ps1'
                 b64_data = base64.b64encode(out_data)
                 script = script_template % (powershell._escape(out_path),
                                             offset, b64_data, in_size)
                 vvvv("WINRM PUT %s to %s (offset=%d size=%d)" %
                      (in_path, out_path, offset, len(out_data)),
                      host=self.host)
                 cmd_parts = powershell._encode_script(script, as_list=True)
                 result = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
                 if result.status_code != 0:
                     raise IOError(result.std_err.encode('utf-8'))
             except Exception:
                 traceback.print_exc()
                 raise errors.AnsibleError("failed to transfer file to %s" %
                                           out_path)
コード例 #27
0
ファイル: chroot.py プロジェクト: xuyeli2002/ansible
    def put_file(self, in_path, out_path):
        ''' transfer a file from local to chroot '''

        if not out_path.startswith(os.path.sep):
            out_path = os.path.join(os.path.sep, out_path)
        normpath = os.path.normpath(out_path)
        out_path = os.path.join(self.chroot, normpath[1:])

        vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
        if not os.path.exists(in_path):
            raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
        try:
            shutil.copyfile(in_path, out_path)
        except shutil.Error:
            traceback.print_exc()
            raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" % out_path)
コード例 #28
0
 def put_file(self, in_path, out_path):
     if _winrm_hacks:
         out_path = _winrm_hacks.fix_slashes(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)
     buffer_size = 1024  # FIXME: Find max size or optimize.
     with open(in_path) as in_file:
         in_size = os.path.getsize(in_path)
         for offset in xrange(0, in_size, buffer_size):
             try:
                 out_data = in_file.read(buffer_size)
                 if offset == 0:
                     if out_data.lower().startswith(
                             '#!powershell'
                     ) and not out_path.lower().endswith('.ps1'):
                         out_path = out_path + '.ps1'
                 b64_data = base64.b64encode(out_data)
                 script = '''
                     $bufferSize = %d;
                     $stream = [System.IO.File]::OpenWrite("%s");
                     $stream.Seek(%d, [System.IO.SeekOrigin]::Begin) | Out-Null;
                     $data = "%s";
                     $buffer = [System.Convert]::FromBase64String($data);
                     $stream.Write($buffer, 0, $buffer.length) | Out-Null;
                     $stream.SetLength(%d) | Out-Null;
                     $stream.Close() | Out-Null;
                 ''' % (buffer_size, self._winrm_escape(out_path), offset,
                        b64_data, in_size)
                 cmd_parts = self._winrm_get_script_cmd(script)
                 result = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
                 if result.status_code != 0:
                     raise RuntimeError(result.std_err.encode('utf-8'))
                 script = u''
             except Exception:  # IOError?
                 traceback.print_exc()
                 raise errors.AnsibleError("failed to transfer file to %s" %
                                           out_path)
コード例 #29
0
    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)

        host = self.host
        if self.ipv6:
            host = '[%s]' % host

        remote_cmd, prompt, success_key = self._su_sudo_cmd(
            self._lxc_cmd('cat > %s; echo -n done' % pipes.quote(out_path)))

        cmd = self._password_cmd()
        cmd += ['ssh'] + self.common_args + [host, remote_cmd]

        (p, stdin) = self._run(cmd, True)
        self._send_password()
        if self.runner.become and self.runner.become_pass:
            (no_prompt_out, no_prompt_err) = self.send_su_sudo_password(
                p, stdin, success_key, True, prompt)

        com = self.CommunicateCallbacks(self.runner,
                                        open(in_path, 'r'),
                                        sudoable=True,
                                        prompt=prompt)
        returncode = self._communicate(p,
                                       stdin,
                                       callbacks=(com.stdin_cb, com.stdout_cb,
                                                  com.stderr_cb))

        if com.stdout[-4:] != 'done':
            raise errors.AnsibleError("failed to transfer file to %s" %
                                      out_path)

        if returncode != 0:
            raise errors.AnsibleError(
                "failed to transfer file to %s:\n%s\n%s" %
                (out_path, stdout, stderr))
コード例 #30
0
    def put_file(self, in_path, out_path):
        """ transfer a file from local to lxc """

        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)
        try:
            src_file = open(in_path, "rb")
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to open file to %s" % in_path)

        def write_file(args):
            dst_file = open(out_path, 'wb')
            shutil.copyfileobj(src_file, dst_file)

        try:
            self.container.attach_wait(write_file, None)
        except IOError:
            traceback.print_exc()
            raise errors.AnsibleError("failed to transfer file to %s" %
                                      out_path)