Python 脚本学习笔记(五)集中式病毒扫描,端口扫描以及分段数据库操作

简介:

      Clam AntiVirus是一个免费而且开放源码的防毒软件,软件与病毒库的更新由开源社区免费发布,目前ClamdAV主要为Linux、Uinux系统提供病毒扫描查杀pyClamad是一个python的第三方模块,可让python直接使用ClamAV病毒扫描守护进程clamd来实现一个高效的病毒检测功能。


一、实现集中式的病毒扫描

1、安装clamavp clamd 服务的相关程序包

yum install clamav clamd clamav-update -y

chkconfig clamd on

更新病毒库

/usr/bin/freshclam

更改配置文件修改监听地址到所有网络,启动服务

sed -i -e '/^TCPAddr/{ s/127.0.0.1/0.0.0.0/;}' /etc/clamd.conf

/etc/init.d/clamd start


2、安装pyClamd模块

pip2.7  install pyClamd


工作原理:管理服务器通过python发出多线程指令连接业务服务器的3310端口,执行病毒扫描,然后返回结果给管理服务器。 业务服务器必须安装clamd相关程序包,并启动服务监听在3310端口才能正常收到指令;


实现代码:

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import  time
import  pyclamd
from  threading  import  Thread
 
class  Scan(Thread):  #继承多线程Thread类
 
     def  __init__ ( self ,IP,scan_type, file ):
         """构造方法"""
         Thread.__init__( self )
         self .IP  =  IP
         self .scan_type = scan_type
         self . file  =  file
         self .connstr = ""
         self .scanresult = ""
 
 
     def  run( self ):
         """多进程run方法"""
 
         try :
             cd  =  pyclamd.ClamdNetworkSocket( self .IP, 3310 )
             """探测连通性"""
             if  cd.ping():
                 self .connstr = self .IP + " connection [OK]"
                 """重载clamd病毒特征库"""
                 cd. reload ()
                 """判断扫描模式"""
                 if  self .scan_type = = "contscan_file" :
                     self .scanresult = "{0}\n" . format (cd.contscan_file( self . file ))
                 elif  self .scan_type = = "multiscan_file" :
                     self .scanresult = "{0}\n" . format (cd.multiscan_file( self . file ))
                 elif  self .scan_type = = "scan_file" :
                     self .scanresult = "{0}\n" . format (cd.scan_file( self . file ))
                 time.sleep( 1 )
             else :
                 self .connstr = self .IP + " ping error,exit"
                 return
         except  Exception,e:
             self .connstr = self .IP + " " + str (e)
 
 
IPs = [ '192.168.1.21' , '192.168.1.22' #扫描主机的列表
scantype = "multiscan_file"  #指定扫描模式
scanfile = "/data/www"  #指定扫描路径
i = 1
threadnum = 2  #指定启动的线程数
scanlist  =  []  #存储Scan类线程对象列表
 
for  ip  in  IPs:
 
     """将数据值带入类中,实例化对象"""
     currp  =  Scan(ip,scantype,scanfile)
     scanlist.append(currp)  #追加对象到列表
 
"""当达到指定的线程数或IP列表数后启动线程"""
     if  i % threadnum = = 0  or  i = = len (IPs):
         for  task  in  scanlist:
             task.start()  #启动线程
 
         for  task  in  scanlist:
             task.join()  #等待所有子线程退出,并输出扫描结果
             print  task.connstr  #打印服务器连接信息
             print  task.scanresult  #打印结果信息
         scanlist  =  []   
     i + = 1


二、使用python-nmap模块实现一个高效的端口扫描器

需要依赖nmap和python-nmap;

yum install nmap

pip2.7 install python-nmap


实现代码:

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  sys
import  nmap
 
scan_row = []
input_data  =  raw_input ( 'Please input hosts and port: ' )
scan_row  =  input_data.split( " " )
if  len (scan_row)! = 2 :
     print  "Input errors,example \"192.168.1.0/24 80,443,22\""
     sys.exit( 0 )
hosts = scan_row[ 0 ]     #接收用户输入的主机
port = scan_row[ 1 ]     #接收用户输入的端口
 
try :
     nm  =  nmap.PortScanner()     #创建端口扫描对象
except  nmap.PortScannerError:
     print ( 'Nmap not found' , sys.exc_info()[ 0 ])
     sys.exit( 0 )
except :
     print ( "Unexpected error:" , sys.exc_info()[ 0 ])
     sys.exit( 0 )
 
try :
     nm.scan(hosts = hosts, arguments = ' -v -sS -p ' + port)     #调用扫描方法,参数指定扫描主机hosts,nmap扫描命令行参数arguments
except  Exception,e:
     print  "Scan erro:" + str (e)
     
for  host  in  nm.all_hosts():     #遍历扫描主机
     print ( '----------------------------------------------------' )
     print ( 'Host : %s (%s)'  %  (host, nm[host].hostname()))     #输出主机及主机名
     print ( 'State : %s'  %  nm[host].state())     #输出主机状态,如up、down
 
     for  proto  in  nm[host].all_protocols():     #遍历扫描协议,如tcp、udp
         print ( '----------' )
         print ( 'Protocol : %s'  %  proto)     #输入协议名
 
         lport  =  nm[host][proto].keys()     #获取协议的所有扫描端口
         lport.sort()     #端口列表排序
         for  port  in  lport:     #遍历端口及输出端口与状态
             print ( 'port : %s\tstate : %s'  %  (port, nm[host][proto][port][ 'state' ]))


三、实现一个程序完成取MySQL数据导出txt,完成压缩,传FTP服务器,自动删除过期数据。


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
#!/usr/local/python27/bin/python2.7
#coding:utf-8
import  os
import  sys
import  pymysql
import  ftplib
import  commands
import  time
import  datetime
 
"""从数据库获取数据"""
def  sql(user,passwd,host,db):
     conn  =  pymysql.connect(host = host,user = user,password = passwd,db = db)
     cur  =  conn.cursor()
     cur.execute( "select count(*) from ucenter_member;" )
     result_num  =  cur.fetchall()
     """由于返回的数据是一个元组,下面的格式转换用于去除括号"""
     total_num  =  int ( str (result_num).lstrip( '((' ).rstrip( ',),)' ))
     """总行数 / 每次取数据的行数 = 需要取的次数 + 1 是因为怕不能整除可以把剩下的数据都取出"""
     linesum  =  (total_num / 5000 + 1 )
     =  0
     while  ( j < linesum ):
         result_num  =  cur.execute( "SELECT id,login,reg_time,last_login_time,type from ucenter_member limit" + ' ' + str ( int (j * 5000 )) + ',' + str ( 5000 ) + ';' )
         data  =  cur.fetchall()
     """定义输出的文件对象"""    
         outfile  =  open ( '/alidata/data_analyse/ucenter-%s' %  time.strftime( '%Y-%m-%d' ,time.localtime(time.time())) + '.txt' , 'a+' )
         for  in  range (result_num):            
             out  =  str (data[i]).strip( '()' ) + '\n'
             outfile.write(out) 
         j + = 1
     outfile.close()      
     outfilename  =  ( 'ucenter-%s' %  time.strftime( '%Y-%m-%d' ,time.localtime(time.time())) + '.txt' )
     return  outfilename
 
"""FTP文件上传函数"""        
def  upload( file ):
     os.chdir( '/alidata/data_analyse/'
     file_path  =  os.path.abspath( file )
     =  open (file_path, 'rb' )
     ftp  =  ftplib.FTP( '115.236.179.166' )
     ftp.login( 'liuyang' , 'liuyang666999' )
     """上传文件,STOR 后面的 %s 定义的是上传后保存的文件名,f为需要上传的文件对象"""
     ftp.storbinary( 'STOR %s' % file ,f)
 
"""文件压缩函数"""
def  gzip(filename):
     os.chdir( '/alidata/data_analyse/' )
     =  commands.getoutput( "zip -9 %s %s"  % (filename + '.zip' ,filename))
     return (filename + '.zip' )
 
"""过期文件删除函数"""
def  Del_file():
     """切换程序的工作目录"""
     os.chdir( '/alidata/data_analyse/' )
     ThreeDaysAgo  =  (datetime.datetime.now()  -  datetime.timedelta(days = 3 ))
     rmtime  =  ThreeDaysAgo.strftime( "%Y-%m-%d" )
     rmfile  =  ( 'ucenter-%s' %  rmtime + '.txt' )
     rmfile2  =  ( 'ucenter-%s' %  rmtime + '.txt.zip' )
     if  os.path.exists(rmfile):
         os.remove(rmfile)
     if  os.path.exists(rmfile2):
         os.remove(rmfile2)
     return
 
if  __name__  = =  '__main__' :
 
     outfilename  =  sql( 'root' , '123456' , '10.1.1.1' , 'hellodb' )
     gzipfile  =  gzip(outfilename)
     starttime  =  datetime.datetime.now()
     upload(gzipfile)
     endtime  =  datetime.datetime.now()
     uptime  =  (endtime  -  starttime).seconds
     with  open ( './history.log' , 'a+' ) as f:
         f.write( 'time:%s,upload cost time:%s'  %  (time.strftime( '%Y-%m-%d %H:%M:%S' ,time.localtime(time.time())),uptime) + '\n' )
     Del_file()



本文转自qw87112 51CTO博客,原文链接:http://blog.51cto.com/tchuairen/1698897


相关文章
|
22天前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
205 7
|
2月前
|
数据采集 关系型数据库 MySQL
python爬取数据存入数据库
Python爬虫结合Scrapy与SQLAlchemy,实现高效数据采集并存入MySQL/PostgreSQL/SQLite。通过ORM映射、连接池优化与批量提交,支持百万级数据高速写入,具备良好的可扩展性与稳定性。
|
2月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
235 0
|
6月前
|
SQL 数据库 开发者
Python中使用Flask-SQLAlchemy对数据库的增删改查简明示例
这样我们就对Flask-SQLAlchemy进行了一次简明扼要的旅程,阐述了如何定义模型,如何创建表,以及如何进行基本的数据库操作。希望你在阅读后能对Flask-SQLAlchemy有更深入的理解,这将为你在Python世界中从事数据库相关工作提供极大的便利。
616 77
|
8月前
|
数据库 Python
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
【YashanDB知识库】python驱动查询gbk字符集崖山数据库CLOB字段,数据被驱动截断
|
关系型数据库 MySQL 数据库连接
python脚本:连接数据库,检查直播流是否可用
【10月更文挑战第13天】本脚本使用 `mysql-connector-python` 连接MySQL数据库,检查 `live_streams` 表中每个直播流URL的可用性。通过 `requests` 库发送HTTP请求,输出每个URL的检查结果。需安装 `mysql-connector-python` 和 `requests` 库,并配置数据库连接参数。
260 68
|
10月前
|
存储 NoSQL 数据库连接
在Python程序中实现LevelDB的海量key的分批次扫描
通过本文的步骤,您可以在Python程序中实现对LevelDB海量key的分批次扫描。这样不仅能够有效地管理大规模数据,还可以避免一次性加载过多数据到内存中,提高程序的性能和稳定性。希望这篇指南能为您的开发工作提供实用的帮助。
242 28
|
8月前
|
SQL 关系型数据库 数据库连接
|
11月前
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
1066 15
|
网络协议 Java Linux
PyAV学习笔记(一):PyAV简介、安装、基础操作、python获取RTSP(海康)的各种时间戳(rtp、dts、pts)
本文介绍了PyAV库,它是FFmpeg的Python绑定,提供了底层库的全部功能和控制。文章详细讲解了PyAV的安装过程,包括在Windows、Linux和ARM平台上的安装步骤,以及安装中可能遇到的错误和解决方法。此外,还解释了时间戳的概念,包括RTP、NTP、PTS和DTS,并提供了Python代码示例,展示如何获取RTSP流中的各种时间戳。最后,文章还提供了一些附录,包括Python通过NTP同步获取时间的方法和使用PyAV访问网络视频流的技巧。
2988 4
PyAV学习笔记(一):PyAV简介、安装、基础操作、python获取RTSP(海康)的各种时间戳(rtp、dts、pts)

推荐镜像

更多