Examples of Python automated operations scripts

Source: Internet
Author: User

1. Enumerate the files in the current directory and all subdirectories and print out the absolute path
#!/usr/bin/python
# Coding=utf8

Import OS
Import Sys

If Len (SYS.ARGV) < 2:
Filepath= "."
Else
FILEPATH=SYS.ARGV[1]

For Root,dirs,files in Os.walk (filepath):
For filename in Files:
Path=os.path.join (Root,filename)
Print path

2. Write a function that calculates all the numbers in the string and
#!/usr/bin/python
# Coding=utf8

Import Sys

Number= "123456"

def numsum (num):
Sum=0
If Len (num) > 0:
For I in range (len (num)):
If num[i] > ' 0 ' and num[i] < ' 9 ':
Sum=sum+int (Num[i])
Print "sum=%s"% sum
Else
Sys.exit (1)

if __name__ = = ' __main__ ':
Numsum (number)

3. Generate a file every day and write the usage of the disk to this file, the file name is date format (YYYY-MM-DD), such as 2018-06-10.log
#!/usr/bin/python
# Coding=utf8

Import time
Import OS
Import getopt
Import Sys

Disk_path= "/root/disk"
Memory_path= "/root/memory"

If not os.path.exists (Disk_path):
Os.makedirs (Disk_path)

If not os.path.exists (Memory_path):
Os.makedirs (Memory_path)

def Disk (time):
Status=os.popen (' DF-HTP '). ReadLines ()
A= '. Join (status)
F=open ('/root/disk/' +time+ '. Log ', ' W ')
F.write (a)
F.close ()

def Memory (time):
Status=os.popen (' Free-g '). ReadLines ()
A= '. Join (status)
F=open ('/root/memory/' +time+ '. Log ', ' W ')
F.write (a)
F.close ()

Time = Time.strftime ("%y-%m-%d-%h:%m:%s")
Options,args = Getopt.getopt (sys.argv[1:], '-d-m ', [' disk_status ', ' memory_status '])
For Opt_name,opt_value in Options:
If Opt_name in ('-d ', '--disk_status '):
Try
Disk (Time)
Print "Disk_status complete"
Exit ()
Except
Print "Fail"
If Opt_name in ('-M ', '--memory_status '):
Try
Memory (Time)
Print "Memory_status complete"
Exit ()
Except
Print "Fail"

4. From the Nginx log to count the number of visits per IP, the number of visits more than 10 times the IP, using the firewall to prohibit the use, and send mail, three days after the limit is opened,
#!/usr/bin/python
#coding =utf8

Import OS
Import subprocess
From Email.mime.text import Mimetext
Import Smtplib

refuse_ip = '/etc/nginx/refuse_nginx '
sender = ' [email protected] '
receiver = ' [email protected] '
Password = ' 123456 '
Subject = ' Nginx IP refuse '

def SendMail (IP):
Try
Print "11111"
Content = Ip+ ' is refuse '
msg = mimetext (content, ' plain ', ' utf-8 ')
msg[' from ' = Sender
Msg[' to '] = Receiver
msg[' Subject '] = Subject
Server=smtplib. SMTP (' localhost ')
Server.sendmail (sender,receiver,msg.as_string ())
Print "Sent successfully"
Except Smtplib. Smtpexception:
Print "Send Failed"

If not os.path.exists (REFUSE_IP):
Os.mknod (REFUSE_IP)

def nginx_protect (IP):
F=open (refuse_ip, ' r+ ')
Cmd= ' iptables-a input-p tcp--dport 80-s ' +ip+ '-j DROP '
Cmd2= ' at now + 1 minutes << eof\niptables-d input-p tcp--dport 80-s ' +ip+ '-j drop\nsed-i ' s/' +ip+ '//'/etc/ngi Nx/refuse_nginx\neof '
For I in F:
If IP not in I:
F.write (IP)
Os.popen (CMD)
Os.popen (CMD2)
SendMail (IP)
Print ("IP limit Succeeded")

List=[]
Nginx_file= "/var/log/nginx/access.log"
F=file (Nginx_file). ReadLines ()
For I in F:
Nginx_ip=i.split () [0]
List.append (NGINX_IP)
Nginxip=set (list)
For J in Nginxip:
Num=list.count (j)
If num > 10:
Nginx_protect (j)
Print "ip:%s num:%s"% (j,num)

5. Write a script to calculate the amount of memory consumed by all processes
#!/usr/bin/python
# Coding=utf8

Import OS

List=[]
cmd= ' PS aux '
Sum=0
Status=os.popen (cmd). ReadLines ()
For I in Status:
A=i.split () [5]
List.append (a)
For I in List[1:-1]:
Sum=sum+int (i)
Print "%S:%SB"% (list[0],sum)

7.MySQL Status Monitoring
#!/usr/bin/python
#coding =utf8

Import MySQLdb

host= "localhost"
User= "WJQ"
Passwd= "123456"
db= "Test"

Com_insert= "show global status Like ' Com_insert ';"
Com_update= "show global status Like ' Com_update ';"
Com_select= "show global status Like ' Com_select ';"
Com_delete= "show global status Like ' Com_delete ';"
Open_tables= "show global status Like ' Open_tables ';"
Qcache_hits= "show global status Like ' Qcache_hits ';"

def getconn (host,user,passwd,db):
Try
conn = MySQLdb.connect (host,user,passwd,db)
Return conn
Except
Print ("Database connection Failed")

def getValue (conn,query):
cursor = Conn.cursor ()
Getnum = cursor.execute (query)
If Getnum > 0:
data = Cursor.fetchone ()
return int (data[1])

if __name__ = = ' __main__ ':
Conn=getconn (HOST,USER,PASSWD,DB)
Com_insert=getvalue (Conn,com_insert)
Com_update=getvalue (Conn,com_update)
Com_select=getvalue (Conn,com_select)
Com_delete=getvalue (Conn,com_delete)
Open_tables=getvalue (Conn,open_tables)
Qcache_hits=getvalue (Conn,qcache_hits)
Print "\t*****mysql status*****"
Print "\tcom_insert:%s\n"% Com_insert
Print "\tcom_update:%s\n"% com_update
Print "\tcom_select:%s\n"% com_select
Print "\tcom_delete:%s\n"% com_delete
Print "\topen_tables:%s\n"% open_tables
Print "\tqcache_hits:%s\n"% qcache_hits

8. Custom password length, generate random password
#!/usr/bin/python
# Coding=utf8
Import Random

List=[]
def Passwd (num):
For I in range (int (num)):
A=random.randrange (0,int (num))
if i = = A:
B1=random.randint (0,9)
List.append (STR (B1))
Else
B2=CHR (Random.randint (65,90))
List.append (B2)
B3= '. Join (list)
Return B3

if __name__ = = ' __main__ ':
Num=raw_input ("The length of the generated password is:")
PASSWORD=PASSWD (num)
Print password

9.python implementation of MySQL Zabbix monitoring script

#!/usr/bin/python
#coding =utf8

Import MySQLdb
Import Sys

host= "localhost"
User= "WJQ"
Passwd= "123456"
db= "Test"
Com_insert= "show global status Like ' Com_insert ';"
Com_update= "show global status Like ' Com_update ';"
Com_select= "show global status Like ' Com_select ';"
Com_delete= "show global status Like ' Com_delete ';"
Open_tables= "show global status Like ' Open_tables ';"
Qcache_hits= "show global status Like ' Qcache_hits ';"

def getconn (host,user,passwd,db):
Try
A = MySQLdb.connect (host,user,passwd,db)
Return a
Except
Print "Database connection Failed"

def getValue (conn,query):
Try
cursor = Conn.cursor ()
Getnum = cursor.execute (query)
If Getnum > 0:
data = Cursor.fetchone ()
return int (data[1])
Except
Print "Query Failed"

conn = Getconn (host,user,passwd,db)
If sys.argv[1] = = ' Insert ':
Com_insert = GetValue (Conn,com_insert)
Print Com_insert
Elif sys.argv[1] = = ' Delete ':
Com_delete = GetValue (conn,com_delete)
Print Com_delete
Elif sys.argv[1] = = ' SELECT ':
Com_select = GetValue (conn,com_select)
Print Com_select
Elif sys.argv[1] = = ' Update ':
Com_update = GetValue (conn,com_update)
Print Com_update
Elif sys.argv[1] = = ' Table_num ':
Open_tables = GetValue (conn,open_tables)
Print Open_tables
Elif sys.argv[1] = = ' Cache_hit ':
Qcache_hits = GetValue (conn,qcache_hits)
Print Qcache_hits

Examples of Python automated operations scripts

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.