python备份脚本

脚本以目录或者文件的绝对路径为参数,可以有多个参数

#!/usr/bin/python
# -*- #coding:cp936

import os
import sys
import glob
import shutil
import time
import datetime
import tarfile
from ftplib import FTP

def getip():
    cmd3 = "/sbin/ifconfig eth0 |grep \"inet addr:\" |awk \'{print $2}\'|cut -c 6-"
    ip = os.popen(cmd3).read().rstrip()
    fileip = ip
    return fileip

def mkdir(path):
    path=path.strip()
    path=path.rstrip("\\")
    isExists=os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return True
    else:
        return False

def ftp(bakfile):
    ftp=FTP()
    ftp.set_debuglevel(2)
    ftp.connect('FTP服务器IP','21')
    ftp.login('用户名','密码')
    ftp.cwd('docs_bak')
    bufsize = 1024
    file_handler = open(bakfile,'rb')
    ftp.storbinary('STOR %s' % os.path.basename(bakfile),file_handler,bufsize)
    ftp.set_debuglevel(0)
    file_handler.close()
    ftp.quit()

def main(dirname):
    global stamptoday
    timestamp = datetime.datetime.strftime(datetime.datetime.today() - datetime.timedelta(3),"%Y-%m-%d")
    mkdir('/usr/local/docs_bak/')
    delfile = '/usr/local/docs_bak/*' + timestamp + '.tar.gz'
    if glob.glob(delfile):
        os.system('/bin/rm ' + delfile)
    stamptoday = datetime.date.today().isoformat()
    today = time.time()
    bakfile = '/usr/local/docs_bak/' + getip() + dirname.replace('/', '_') + '_' + str(stamptoday) + ".tar.gz"
    tarcmd = '/bin/tar -zcf ' + bakfile + ' ' + dirname
    os.system(tarcmd)
    ftp(bakfile)

if len(sys.argv) < 2:
    print 'Error: One parameter at least!!!'
for dirname in sys.argv[1:]:
    main(dirname)

 

Linux服务器登陆IP监控脚本

#!/usr/bin/python
# -*- #coding:cp936

import os
import time
import datetime
import string
import email
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from ip_area import IPInfo

def SendMail():

    cmd = "/sbin/ifconfig eth0 |grep \"inet addr:\" |awk \'{print $2}\'|cut -c 6-"
    localip = os.popen(cmd).read().rstrip()
    mail_to = ["***"]
    mail_host = "***"
    mail_user = "***"
    mail_pass = "***"
    mail_from = "***"
    mail_postfix = "***"
    mail_subject = "Unknow IP address(" + ip + " - " + str(address) + ") login to " + localip + " !!!"
    mail_body = mailbody

    msg = MIMEMultipart()
    body = MIMEText(mail_body,_subtype='plain',_charset='gb2312')
    body = MIMEText(mail_body,_subtype='plain',_charset='utf-8')
    msg.attach(body)
    
    msg['Subject'] = mail_subject
    msg['From'] = mail_from
    msg['To'] = ";".join(mail_to)
    
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_from, mail_to, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False  

def loginMon():
    global ip
    global address
    ip = os.popen("last |head -1|awk '{print $3}'").read()[0:-1]
    print ip
    areaInfo=IPInfo('/usr/local/bin/QQWry.dat')
    (c, a) = areaInfo.getIpAddr( areaInfo.str2ip(ip) )
    address = c + a
    #print c
    #把已知的允许登陆IP写在iplist中
    iplist = ['13.14.78.16', '1.13.20.7']
    if '192.168.' not in ip and ip not in iplist:
        #print 'aaaaaaa'
        if c.find(u'±±æ©'.encode('utf-8')) == -1 and c.find(u'≥…∂º'.encode('utf-8')) == -1: 
            #print 'bbbbbb'
            SendMail()

def main():
    os.system('grep "Failed password for" /var/log/auth.log > /var/log/last.txt')
    os.system("echo '######################## I ## AM ## THE ## DIVIDING ## LINE ############################' >> /var/log/last.txt ")
    os.system('/usr/bin/last >> /var/log/last.txt')
    textfile = '/var/log/last.txt'
    global mailbody
    mailbody = 'Recent login information as follows:\n\n' 
    f = open(textfile,'rb')
    line = f.readlines()
    f.close()
    for x in line:
        mailbody = mailbody + x
    loginMon()

main()

 

Ubuntu失败登陆监测脚本

#!/usr/bin/python
# -*- coding: cp936 -*-

import os
import time
import datetime
import string
import email
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def SendMail():

    cmd = "/sbin/ifconfig eth0 |grep \"inet addr:\" |awk \'{print $2}\'|cut -c 6-"
    localip = os.popen(cmd).read().rstrip()
    mail_to = ["****"]
    mail_host = "****"
    mail_user = "****"
    mail_pass = "****"
    mail_from = "****"
    mail_postfix = "****"
    mail_subject = "Failed Login Attempts Warning-" + localip +" !!!"
    mail_body = mailbody

    msg = MIMEMultipart()
    body = MIMEText(mail_body,_subtype='plain',_charset='gb2312')
    body = MIMEText(mail_body,_subtype='plain',_charset='utf-8')
    msg.attach(body)
    
    msg['Subject'] = mail_subject
    msg['From'] = mail_from
    msg['To'] = ";".join(mail_to)
    
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(mail_from, mail_to, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False  

def handlefile():
    list = []
    f = open('/usr/local/bin/FL_1.txt', 'r')
    while True:               
        line = f.readline()           
        if len(line) == 0:
            break
        list.append(line[0:-1])
    f.close()
    print list

    if len(list) != 0:
        os.system('/bin/cat /dev/null > /usr/local/bin/FL_2.txt')
        ff = open('/usr/local/bin/FL_2.txt', 'a')
        for i in range(0, len(list)):
            if int(list[i][0]) > 3:
                print >> ff, list[i]
        ff.close()
        if len(open('/usr/local/bin/FL_2.txt').read()) != 0:
            print 'len of FL_2.txt is ' + str(len(open('/usr/local/bin/FL_2.txt').read()))
            global mailbody
            mailbody = 'Failed login attempts as follows in the last hour:\n\n\nCount    IP\n\n' 
            fff = open('/usr/local/bin/FL_2.txt', 'rb')
            line = fff.readlines()
            fff.close()
            for x in line:
                mailbody = mailbody + x
            print mailbody
            SendMail()

def main():
    os.system('''grep 'Failed password for' /var/log/auth.log|grep "`date +%d' '%H`"|awk '{print $11}'|uniq -c|sed 's/^[ \t]*//g' > /usr/local/bin/FL_1.txt''')
    handlefile()

main()

 

python的pymssql插件在ubuntu12.04上查询为空?

下载pymssql-2.0.0b1-dev-20111019.tar.gz          (http://pymssql.googlecode.com/files/pymssql-2.0.0b1-dev-20111019.tar.gz)

gzip -d pymssql-2.0.0b1-dev-20111019.tar.gz
tar -xvf pymssql-2.0.0b1-dev-20111019.tar
wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg          (在’/home/anyuser/software/pymssql-2.0.0b1-dev-20111019’目录下)
重命名setuptools-0.6c11-py2.7.egg为setuptools-0.6c9-py2.7.egg
运行python setup.py build报错:ImportError: No module named setuptools

apt-get install python-setuptools

运行python setup.py build报错:ImportError: No module named Cython.Distutils

apt-get install cython

python setup.py build

python setup.py install