当前位置: 首页>>代码示例>>Python>>正文


Python pyclamd.ClamdUnixSocket方法代码示例

本文整理汇总了Python中pyclamd.ClamdUnixSocket方法的典型用法代码示例。如果您正苦于以下问题:Python pyclamd.ClamdUnixSocket方法的具体用法?Python pyclamd.ClamdUnixSocket怎么用?Python pyclamd.ClamdUnixSocket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyclamd的用法示例。


在下文中一共展示了pyclamd.ClamdUnixSocket方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: file_virus_validator

# 需要导入模块: import pyclamd [as 别名]
# 或者: from pyclamd import ClamdUnixSocket [as 别名]
def file_virus_validator(form, field):
    """ Checks for virus in the file from flask request object,
    raises wtf.ValidationError if virus is found else None. """

    if not pagure_config["VIRUS_SCAN_ATTACHMENTS"]:
        return
    from pyclamd import ClamdUnixSocket

    if (
        field.name not in flask.request.files
        or flask.request.files[field.name].filename == ""
    ):
        # If no file was uploaded, this field is correct
        return
    uploaded = flask.request.files[field.name]
    clam = ClamdUnixSocket()
    if not clam.ping():
        raise wtforms.ValidationError(
            "Unable to communicate with virus scanner"
        )
    results = clam.scan_stream(uploaded.stream.read())
    if results is None:
        uploaded.stream.seek(0)
        return
    else:
        result = results.values()
        res_type, res_msg = result
        if res_type == "FOUND":
            raise wtforms.ValidationError("Virus found: %s" % res_msg)
        else:
            raise wtforms.ValidationError("Error scanning uploaded file") 
开发者ID:Pagure,项目名称:pagure,代码行数:33,代码来源:forms.py

示例2: _run

# 需要导入模块: import pyclamd [as 别名]
# 或者: from pyclamd import ClamdUnixSocket [as 别名]
def _run(self, scanObject, result, depth, args):
        '''
        Arguments:
        unixsocket     -- Path to the clamd unix socket (str)
        maxbytes       -- Maximum number of bytes to scan (0 is unlimited) (int)

        Returns:
        Flags           -- Virus name hits
        Metadata        -- Unix socket or daemon errors
        '''
        moduleResult = []

        unix_socket = str(get_option(args, 'unixsocket', 'scanclamavunixsocket', '/var/run/clamav/clamd.ctl'))
        max_bytes = int(get_option(args, 'maxbytes', 'scanclamavmaxbytes', 20000000))

        # Connect to daemon
        if not self.clam:
            try:
                self.clam = pyclamd.ClamdUnixSocket(filename=unix_socket)
            except IOError:
                logging.debug('IOError: Cannot connect to clamd unix socket file')
                scanObject.addMetadata(self.module_name, 'Error', 'IOError: clamd socket')
                raise

        try:
            # Scan the buffer with clamav
            if max_bytes <= 0:
                clam_result = self.clam.scan_stream(scanObject.buffer)
            else:
                clam_result = self.clam.scan_stream(str(buffer(scanObject.buffer, 0, max_bytes)))

            # Process a result
            if clam_result:
                status, virusname = clam_result['stream']
                scanObject.addFlag("%s:%s" % (self.flag_prefix, str(virusname)))
        except ValueError as e:
            scanObject.addMetadata(self.module_name, 'Error', 'ValueError (BufferTooLong): %s' % str(e))
        except IOError as e:
            scanObject.addMetadata(self.module_name, 'Error', 'IOError (ScanError): %s' % str(e))

        return moduleResult 
开发者ID:lmco,项目名称:laikaboss,代码行数:43,代码来源:scan_clamav.py

示例3: _connect_clam

# 需要导入模块: import pyclamd [as 别名]
# 或者: from pyclamd import ClamdUnixSocket [as 别名]
def _connect_clam():
    try:
        clamScanner = pyclamd.ClamdUnixSocket()
        clamScanner.ping()
    except pyclamd.ConnectionError:
        clamScanner = pyclamd.ClamdNetworkSocket()
        try:
            clamScanner.ping()
        except pyclamd.ConnectionError:
            raise ValueError("Unable to connect to clamd")
    return clamScanner 
开发者ID:mitre,项目名称:multiscanner,代码行数:13,代码来源:ClamAVScan.py

示例4: test_upload_issue_virus

# 需要导入模块: import pyclamd [as 别名]
# 或者: from pyclamd import ClamdUnixSocket [as 别名]
def test_upload_issue_virus(self, p_send_email, p_ugt):
        """ Test the upload_issue endpoint. """
        if not pyclamd:
            raise SkipTest()
        p_send_email.return_value = True
        p_ugt.return_value = True

        tests.create_projects(self.session)
        tests.create_projects_git(os.path.join(self.path, "repos"), bare=True)
        tests.create_projects_git(
            os.path.join(self.path, "tickets"), bare=True
        )

        # Create issues to play with
        repo = pagure.lib.query.get_authorized_project(self.session, "test")
        msg = pagure.lib.query.new_issue(
            session=self.session,
            repo=repo,
            title="Test issue",
            content="We should work on this",
            user="pingou",
        )
        self.session.commit()
        self.assertEqual(msg.title, "Test issue")

        user = tests.FakeUser()
        user.username = "pingou"
        with tests.user_set(self.app.application, user):
            csrf_token = self.get_csrf()

            # TODO: Figure a way to enable this test on jenkins
            # Try to attach a virus
            if not os.environ.get("BUILD_ID"):
                with tempfile.NamedTemporaryFile() as eicarfile:
                    eicarfile.write(pyclamd.ClamdUnixSocket().EICAR())
                    eicarfile.flush()
                    with open(eicarfile.name, "rb") as stream:
                        data = {
                            "csrf_token": csrf_token,
                            "filestream": stream,
                            "enctype": "multipart/form-data",
                        }
                        output = self.app.post(
                            "/test/issue/1/upload",
                            data=data,
                            follow_redirects=True,
                        )
                    self.assertEqual(output.status_code, 200)
                    json_data = json.loads(output.get_data(as_text=True))
                    exp = {"output": "notok"}
                    self.assertDictEqual(json_data, exp) 
开发者ID:Pagure,项目名称:pagure,代码行数:53,代码来源:test_pagure_flask_ui_issues.py

示例5: clean

# 需要导入模块: import pyclamd [as 别名]
# 或者: from pyclamd import ClamdUnixSocket [as 别名]
def clean(self, data, initial=None):
        f = super(yatsFileField, self).clean(initial or data)
        if f is None:
            return None
        elif not data and initial:
            return initial

        if settings.FILE_UPLOAD_VIRUS_SCAN and pyclamd:
            # virus scan
            try:
                if not hasattr(pyclamd, 'scan_stream'):
                    cd = pyclamd.ClamdUnixSocket()
                else:
                    pyclamd.init_network_socket('localhost', 3310)
                    cd = pyclamd

                # We need to get a file object for clamav. We might have a path or we might
                # have to read the data into memory.
                if hasattr(data, 'temporary_file_path'):
                    chmod(data.temporary_file_path(), 0o664)
                    result = cd.scan_file(data.temporary_file_path())
                else:
                    if hasattr(data, 'read'):
                        result = cd.scan_stream(data.read())
                    else:
                        result = cd.scan_stream(data['content'])
            except:
                from socket import gethostname
                raise ValidationError(self.error_messages['virus_engine_error'] % gethostname())

            if result:
                msg = ' '.join(result[result.keys()[0]]).replace('FOUND ', '')
                raise ValidationError(self.error_messages['virus_found'] % msg)

        hasher = hashlib.md5()
        # We need to get a file object for clamav. We might have a path or we might
        # have to read the data into memory.
        if hasattr(data, 'temporary_file_path'):
            with open(data.temporary_file_path(), 'rb') as afile:
                buf = afile.read()
                hasher.update(buf)
        else:
            if hasattr(data, 'read'):
                data.seek(0)
                buf = data.read()
                hasher.update(buf)
            else:
                hasher.update(data['content'].read())
        f.hash = hasher.hexdigest()

        return f 
开发者ID:mediafactory,项目名称:yats,代码行数:53,代码来源:fields.py


注:本文中的pyclamd.ClamdUnixSocket方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。