Python executes shell to get hardware parameters and writes them to mysql

Source: Internet
Author: User
This article mainly introduces how to write hardware parameters to mysql by executing shell in python. it can read server hardware information and write data to the database, which is of great practical value, for more information about how to write hardware parameters to mysql, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

Recently, you need to obtain various server parameters, including cpu, memory, disk, and model information. Hyperic HQ, Nagios, and Snmp have been used for trial. they all have powerful functions, but they are either too powerful or too heavy.

Therefore, you can use python to execute shell to obtain the information. There are three methods for python to execute shell scripts:

1. OS. system ()

The code is as follows:

OS. system ('Ls ')
# If the returned result is 0 or 1, the command output cannot be obtained.


2. OS. popen ()

The code is as follows:

Output = OS. popen ('Ls ')
Print output. read ()
# Command output is printed, but the returned value is not obtained.


3. commands. getstatusoutput ()

The code is as follows:

(Status, output) = commands. getstatusoutput ('Ls ')
Print status, output
# Print the return value and command output


You can select one of the methods as needed. The following is a program in which python executes shell to obtain hardware parameters and write them into mysql, and regularly updates them:

The code is as follows:


'''
Created on Dec 10,201 4

@ Author: liufei
'''
# Coding = UTF-8
Import time, sched, OS, string
From datetime import datetime
Import MySQLdb

S = sched. schedep (time. time, time. sleep)

Def event_func ():
Try:
# Host name
Name = OS. popen ("" hostname "). read ()
# Number of CPUs
Cpu_num = OS. popen ("" cat/proc/cpuinfo | grep processor | wc-l ""). read ()
# Memory size
Mem = OS. popen ("" free | grep Mem | awk '{print $2}' "). read ()
# Machine brand
Brand = OS. popen ("dmidecode | grep 'bad' | head-1 | awk-F: '{print $2}'"). read ()
# Model
Model = OS. popen ("dmidecode | grep 'product name' | head-1 | awk-F: '{print $2}'"). read ()
# Disk size
Storage = OS. popen ("fdisk-l | grep 'disk/dev/sD' | awk' BEGIN {sum = 0} {sum = sum + $3} END {print sum }' """). read ()
# Mac address
Mac = OS. popen ("" ifconfig-a | grep HWaddr | head-1 | awk '{print $5}' "). read ()

Name = name. replace ("\ n", ""). lstrip ()
Cpu_num = cpu_num.replace ("\ n", ""). lstrip ()
Memory_gb = round (string. atof (mem. replace ("\ n", ""). lstrip ()/1000.0/1000.0, 1)
Brand = brand. replace ("\ n", ""). lstrip ()
Model = model. replace ("\ n", ""). lstrip ()
Storage_gb = storage. replace ("\ n", ""). lstrip ()
Mac = mac. replace ("\ n", ""). lstrip ()

Print name
Print cpu_num
Print memory_gb
Print storage_gb
Print brand
Print model
Print mac

Conn = MySQLdb. connect (host = 'XX. xx. xx. xx', user = 'username', passwd = 'password', db = 'dbname', port = 3306)
Cur = conn. cursor ()
Cur.exe cute ('select mac from servers where mac = % s', mac)
Data = cur. fetchone ()

If data is None:
Value = [name, brand, model, memory_gb, storage_gb, cpu_num, mac, datetime. now (), datetime. now ()]
Cur.exe cute ("insert into servers (name, brand, model, memory_gb, storage_gb, cpu_num, mac, created_at, updated_at) values (% s, % s, % s, % s) ", value)
Else:
Value1 = [name, brand, model, memory_gb, storage_gb, cpu_num, datetime. now (), mac]
Cur.exe cute ("update servers set name = % s, brand = % s, model = % s, memory_gb = % s, storage_gb = % s, cpu_num = % s, updated_at = % s where mac = % s ", value1)

Conn. commit ()
Cur. close ()
Conn. close ()

Counter T MySQLdb. Error, e:
Print "Mysql Error % d: % s" % (e. args [0], e. args [1])

Def perform (inc ):
S. enter (inc, 0, perform, (inc ,))
Event_func ()

Def mymain (inc = 10 ):
S. enter (0, 0, perform, (inc ,))
S. run ()

If _ name _ = "_ main __":
Mymain ()

I hope this article will help you with Python programming.

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.