Python Script Learning Notes (v) centralized virus scanning, port scanning, and segmented database operations

Source: Internet
Author: User
Tags file upload ftp file python script virus scan

Clam Antivirus is a free and open source antivirus software, software and virus database update by the open source community free release, currently Clamdav mainly for Linux, uinux system to provide virus scanning avira Pyclamad is a python third-party module, Allows Python to use the ClamAV virus scanning daemon CLAMD directly for an efficient virus detection function.


One, to achieve centralized virus scanning

1. Installation of CLAMAVP CLAMD services related packages

Yum Install ClamAV CLAMD clamav-update-y

Chkconfig CLAMD on

Update virus Database

/usr/bin/freshclam

Change profile Modify listener address to all networks, start service

Sed-i-E '/^tcpaddr/{s/127.0.0.1/0.0.0.0/;} '/etc/clamd.conf

/ETC/INIT.D/CLAMD start


2. Installing the PYCLAMD module

pip2.7 Install PYCLAMD


How it works: The Management Server sends multi-threaded instructions through Python to connect to the 3310 port of the Business Server, perform a virus scan, and then return the results to the Management server. The Business Server must install the CLAMD related package and start the service listener on port 3310 to receive the instruction normally;


Implementation code:

#!/usr/bin/env python# -*- coding: utf-8 -*-import timeimport pyclamdfrom  threading import threadclass scan (Thread):  #继承多线程Thread类     def  __init__  (self,ip,scan_type,file):         "" "Construction Method" ""          thread.__init__ (self)          self. ip = ip        self.scan_type=scan_type         self.file = file         Self.connstr= ""         self.scanresult= ""     def  run (self):         "" "Multi-Process Run Method" ""          try:            cd =  Pyclamd. ClamdnetworksoCket (self. ip,3310)              "" "Detection Connectivity" ""              if cd.ping ():                 self.connstr=self. ip+ " connection [ok"                   "" "Overloaded clamd virus Signature Library" "                 cd.reload ()                   "" "Judging scan Mode" ""                  if self.scan_type== "Contscan_file":                     self.scanresult= "{0}\n". Format ( Cd.contscan_file (self.file))    &Nbsp;            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"           &Nbsp;     return        except exception , E:            self.connstr=self. ip+ " " +str (e) ips=[' 192.168.1.21 ', ' 192.168.1.22 ']  #扫描主机的列表scantype = "Multiscan_file"  # Specify scan mode scanfile= "/data/www"   #指定扫描路径i =1threadnum=2  #指定启动的线程数scanlist  = [] # Store Scan class Thread object list for ip in ips:     "" brings data values into class, instantiates object "" "     Currp = scan (Ip,scantype,scanfile)     scanlist.append (CURRP)   #追加对象到列表 "" " Start thread "" "    if i%threadnum==0 or i==len (IPs):   when the specified number of threads or IP list is reached       for task in scanlist:             task.start ()   #启动线程         for  task in scanlist:    &Nbsp;       task.join ()   #等待所有子线程退出, and output scan results              print task.connstr  #打印服务器连接信息              print task.scanresult  #打印结果信息          scanlist = []       i+=1


Second, using the Python-nmap module to achieve an efficient port scanner

Need to rely on nmap and python-nmap;

Yum Install Nmap

pip2.7 Install Python-nmap


Implementation code:

#!/usr/bin/env python# -*- coding: utf-8 -*-import sysimport nmapscan_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)      #调用扫描方法, parameters specify scan host hosts,nmap scan command line parameters argumentsexcept exception,e:    print  "scan  erro: "+str (e)     for host in nm.all_hosts ():     # Traverse Scan host     print ('----------------------------------------------------')      print (' host : %s  (%s) '  %  (Host, nm[host].hostname ()))       #输出主机及主机名     print (' state : %s '  % nm[host].state ())       #输出主机状态, such as Up, Down    for proto in nm[host].all_protocols ():      #遍历扫描协议, such as TCP, Udp        print ('----------')         print (' protocol : %s '  % proto)       #输入协议名         lport = nm[host][proto].keys ()      #获取协议All scan ports         lport.sort ()      #端口列表排序          for port in lport:     #遍历端口及输出端口与状态             print (' Port : %s\tstate  : %s '  %  (port, nm[host][proto][port][' state '))


Third, the realization of a program to complete the MySQL data export txt, complete compression, FTP server, automatically delete expired data.


#!/usr/local/python27/bin/python2.7#coding:utf-8import osimport sysimport pymysqlimport  Ftplibimport commandsimport timeimport datetime "" "Fetch Data from Database" "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 ()      "" "because the returned data is a tuple, The following format conversion is used to remove parentheses "" "    total_num = int (str (result_num). Lstrip (' ('). Rstrip (',),) ')      Total Row  /  number of rows per fetch  =  number of times  + 1  it's because you're afraid that you can't divide the remaining data out. "    linesum =  (total_num/5000+1)     j = 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 ()      "" " Defines the output of the file object "" "            outfile = open (' /alidata/data_analyse/ucenter-%s '% time.strftime ('%y-%m-%d ', Time.localtime (Time.time ())) + '. txt ', ' A + ')         for i in range (Result_num):                          out = str (Data[i]). Strip (' () ') + ' \ n '              outfile.write (out)          j+=1     outfile.close () &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;    outfilename =  (' ucenter-%s '% time.strftime ('%Y-%m-%d ', time.localtime (Time.time ())) + '. txt ')     return outfilename "" "FTP File Upload function" ""          def upload (file):     os.chdir ('/alidata/data_analyse/')       file_path = os.path.abspath (file)     f = open (File_path, ' RB ')     ftp = ftplib. FTP (' 115.236.179.166 ')     ftp.login (' Liuyang ', ' liuyang666999 ')      "" " After uploading the file,stor   %s  definition is the file name after uploading, F is the file object that needs to be uploaded "" "    ftp.storbinary (' stor  %s '%file,f ' "" "File Compression function" "" Def gzip (filename):     os.chdir ('/alidata/data_analyse/')     g = commands.getoutput ("zip -9 %s %s"  % (filename+ '. zip '), FileName)     return (filename+ '. zip ') "" "Expired file deletedFunction "" "Def del_file ():    " "" Switch the working directory of the Program ""     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)     returnif  __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 ()




This article from "Breakthrough Comfort zone" blog, reproduced please contact the author!

Python Script Learning Notes (v) centralized virus scanning, port scanning, and segmented database operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.