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


相关文章
|
前端开发 数据库
会议室管理系统源码(含数据库脚本)
会议室管理系统源码(含数据库脚本)
259 0
|
存储 SQL 关系型数据库
Mysql学习笔记(二):数据库命令行代码总结
这篇文章是关于MySQL数据库命令行操作的总结,包括登录、退出、查看时间与版本、数据库和数据表的基本操作(如创建、删除、查看)、数据的增删改查等。它还涉及了如何通过SQL语句进行条件查询、模糊查询、范围查询和限制查询,以及如何进行表结构的修改。这些内容对于初学者来说非常实用,是学习MySQL数据库管理的基础。
436 6
|
关系型数据库 MySQL Linux
实现MySQL数据库的定时自动备份脚本。
拿走,不谢,这个脚本配方(指引)保证你的数据库数据像蛋糕店一样地天天更新,还能确保老旧的蛋糕(数据)不会堆积满仓库。这下可好,数据安全有保障,数据库管理员也能轻松一点,偶尔闲下来的时候,煮杯咖啡,看个剧岂不美哉?别忘了偶尔检查一下你的自动备份是否正常工作,以防万一蛋糕机器出了点小差错。
917 20
|
Java 数据库
jsp CRM客户管理系统(含数据库脚本以及文档)
jsp CRM客户管理系统(含数据库脚本以及文档)
308 10
|
Java 关系型数据库 MySQL
Java汽车租赁系统源码(含数据库脚本)
Java汽车租赁系统源码(含数据库脚本)
649 4
|
关系型数据库 MySQL 数据库连接
python脚本:连接数据库,检查直播流是否可用
【10月更文挑战第13天】本脚本使用 `mysql-connector-python` 连接MySQL数据库,检查 `live_streams` 表中每个直播流URL的可用性。通过 `requests` 库发送HTTP请求,输出每个URL的检查结果。需安装 `mysql-connector-python` 和 `requests` 库,并配置数据库连接参数。
409 68
|
关系型数据库 Shell 网络安全
定期备份数据库:基于 Shell 脚本的自动化方案
本篇文章分享一个简单的 Shell 脚本,用于定期备份 MySQL 数据库,并自动将备份传输到远程服务器,帮助防止数据丢失。
|
SQL 关系型数据库 数据库连接
|
网络协议 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访问网络视频流的技巧。
4760 4
PyAV学习笔记(一):PyAV简介、安装、基础操作、python获取RTSP(海康)的各种时间戳(rtp、dts、pts)
|
SQL Ubuntu 关系型数据库
Mysql学习笔记(一):数据库详细介绍以及Navicat简单使用
本文为MySQL学习笔记,介绍了数据库的基本概念,包括行、列、主键等,并解释了C/S和B/S架构以及SQL语言的分类。接着,指导如何在Windows和Ubuntu系统上安装MySQL,并提供了启动、停止和重启服务的命令。文章还涵盖了Navicat的使用,包括安装、登录和新建表格等步骤。最后,介绍了MySQL中的数据类型和字段约束,如主键、外键、非空和唯一等。
347 3
Mysql学习笔记(一):数据库详细介绍以及Navicat简单使用

推荐镜像

更多