1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
|
# -*- coding: utf-8 -*-
"""
pyclamd.py - v0.1.1 - 2006.07.15
Author : Alexandre Norman - norman@xael.org
Licence : GPL
Usage :
# Init the connexion to clamd, either :
# Network
pyclamd.init_network_socket('localhost', 3310)
# Unix local socket
#pyclamd.init_unix_socket('/var/run/clamav/clamd.ctl')
# Get Clamscan version
print pyclamd.version()
# Scan a buffer
print pyclamd.scan_stream(pyclamd.EICAR)
# Scan a file
print pyclamd.scan_file('/tmp/test.vir')
Test strings :
^^^^^^^^^^^^
>>> try:
... init_unix_socket('/var/run/clamav/clamd.ctl')
... except ScanError:
... init_network_socket('localhost', 3310)
...
>>> ping()
True
>>> version()[:6]=='ClamAV'
True
>>> scan_stream(EICAR)
{'stream': 'Eicar-Test-Signature FOUND'}
>>> open('/tmp/EICAR','w').write(EICAR)
>>> scan_file('/tmp/EICAR')
{'/tmp/EICAR': 'Eicar-Test-Signature'}
>>> contscan_file('/tmp/EICAR')
{'/tmp/EICAR': 'Eicar-Test-Signature'}
>>> import os
>>> os.remove('/tmp/EICAR')
"""
############################################################################
# Module defined Exceptions
global BufferTooLong
global ScanError
class BufferTooLong(Exception): pass
class ScanError(Exception): pass
# Some global variables
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global EICAR
# Default values for globals
use_socket = None
clamd_SOCKET = "/var/run/clamav/clamd.ctl"
clamd_HOST='127.0.0.1'
clamd_PORT=3310
# Eicar test string (encoded for skipping virus scanners)
EICAR = 'WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5E'.decode('base64') \
+'QVJELUFOVElWSVJVUy1URVNU\nLUZJTEUhJEgrSCo=\n'.decode('base64')
############################################################################
import socket
import types
import string
############################################################################
def init_unix_socket(filename="/var/run/clamav/clamd.ctl"):
"""
Init pyclamd to use clamd unix local socket
filename (string) : clamd file for local unix socket
return : Nothing
May raise :
- TypeError : if filename is not a string
- ValueError : if filename does not allow to ping the server
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
if type(filename)!=types.StringType:
raise TypeError, 'filename should be a string not "%s"' % filename
use_socket = "UNIX"
clamd_SOCKET = filename
ping()
return
############################################################################
def init_network_socket(host='127.0.0.1', port=3310):
"""
Init pyclamd to use clamd network socket
host (string) : clamd server adresse
port (int) : clamd server port
return : Nothing
May raise :
- TypeError : if host is not a string or port is not an int
- ValueError : if the server can not be pingged
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
if type(host)!=types.StringType:
raise TypeError, 'host should be a string not "%s"' % host
if type(port)!=types.IntType:
raise TypeError, 'port should be an integer not "%s"' % port
use_socket = "NET"
clamd_HOST = host
clamd_PORT = port
ping()
return
############################################################################
def ping():
"""
Send a PING to the clamav server, which should reply
by a PONG.
return : True if the server replies to PING
May raise :
- ScanError : if the server do not reply by PONG
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global ScanError
s = __init_socket__()
try:
s.send('PING')
result = s.recv(20000)
s.close()
except:
raise ScanError, 'Could not ping clamd server'
if result=='PONG\n':
return True
else:
raise ScanError, 'Could not ping clamd server'
############################################################################
def version():
"""
Get Clamscan version
return : (string) clamscan version
May raise :
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
s = __init_socket__()
s.send('VERSION')
result = s.recv(20000).strip()
s.close()
return result
############################################################################
def reload():
"""
Force Clamd to reload signature database
return : (string) "RELOADING"
May raise :
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
s = __init_socket__()
s.send('RELOAD')
result = s.recv(20000).strip()
s.close()
return result
############################################################################
def shutdown():
"""
Force Clamd to shutdown and exit
return : nothing
May raise :
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
s = __init_socket__()
s.send('SHUTDOWN')
result = s.recv(20000)
s.close()
return
############################################################################
def scan_file(file):
"""
Scan a file or directory given by filename and stop on virus
file (string) : filename or directory (MUST BE ABSOLUTE PATH !)
return either :
- (dict) : {filename1: "virusname"}
- None if no virus found
May raise :
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global ScanError
s = __init_socket__()
s.send('SCAN %s' % file)
result='...'
dr={}
while result!='':
result = s.recv(20000)
if len(result)>0:
filenm = string.join(result.strip().split(':')[:-1])
virusname = result.strip().split(':')[-1].strip()
if virusname[-5:]=='ERROR':
raise ScanError, virusname
elif virusname[-5:]=='FOUND':
dr[filenm]=virusname[:-6]
s.close()
if dr=={}:
return None
else:
return dr
############################################################################
def contscan_file(file):
"""
Scan a file or directory given by filename
file (string) : filename or directory (MUST BE ABSOLUTE PATH !)
return either :
- (dict) : {filename1: "virusname", filename2: "virusname"}
- None if no virus found
May raise :
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global ScanError
s = __init_socket__()
s.send('CONTSCAN %s' % file)
result='...'
dr={}
while result!='':
result = s.recv(20000)
if len(result)>0:
filenm = string.join(result.strip().split(':')[:-1])
virusname = result.strip().split(':')[-1].strip()
if virusname[-5:]=='ERROR':
raise ScanError, virusname
elif virusname[-5:]=='FOUND':
dr[filenm]=virusname[:-6]
s.close()
if dr=={}:
return None
else:
return dr
############################################################################
def scan_stream(buffer):
"""
Scan a buffer
buffer (string) : buffer to scan
return either :
- (dict) : {filename1: "virusname"}
- None if no virus found
May raise :
- BufferTooLong : if the buffer size exceeds clamd limits
- ScanError : in case of communication problem
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global BufferTooLong
global ScanError
s = __init_socket__()
s.send('STREAM')
port = int(s.recv(200).strip().split(' ')[1])
n=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
n.connect((clamd_HOST, port))
sended = n.send(buffer)
n.close()
if sended<len(buffer):
raise BufferTooLong
result='...'
dr={}
while result!='':
result = s.recv(20000)
if len(result)>0:
filenm = result.strip().split(':')[0]
virusname = result.strip().split(':')[1].strip()
if virusname[-5:]=='ERROR':
raise ScanError, virusname
elif virusname!='OK':
dr[filenm]=virusname
s.close()
if dr=={}:
return None
else:
return dr
############################################################################
def __init_socket__():
"""
This is for internal use
"""
global use_socket
global clamd_HOST
global clamd_PORT
global clamd_SOCKET
global ScanError
if use_socket=="UNIX":
s=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
s.connect(clamd_SOCKET)
except socket.error:
raise ScanError, 'Could not reach clamd using unix socket (%s)' % (clamd_SOCKET)
elif use_socket=="NET":
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((clamd_HOST, clamd_PORT))
except socket.error:
raise ScanError, 'Could not reach clamd using network (%s, %s)' % (clamd_HOST, clamd_PORT)
else:
raise ScanError, 'Could not reach clamd : connexion not initialised'
return s
############################################################################
def __non_regression_test__():
"""
This is for internal use
"""
import doctest
doctest.testmod()
return
############################################################################
# MAIN -------------------
if __name__ == '__main__':
__non_regression_test__()
import os
import sys
## import doctest
## doctest.testmod()
sys.exit(0)
# Print autodoc
if sys.argv[0].find(os.path.sep)==-1:
os.system("pydoc ./"+sys.argv[0])
else:
os.system("pydoc "+sys.argv[0])
sys.exit(0)
#<EOF>######################################################################
|