แสดงบทความที่มีป้ายกำกับ Python แสดงบทความทั้งหมด

วันเสาร์ที่ 25 กรกฎาคม พ.ศ. 2558

[HOW TO] Auto Backup Mysqldump with Python and crontab

[HOW TO] Auto Backup Mysqldump with Python and crontab



        บทความนี้เราจะมาเขียน  สคริปให้ auto mysql backup บน Linux กันนะครับ โดยมีการใช้ ภาษา Python และคำสั่ง crontab สำหรับ ตารางเวลาในการทำงาน

Dowload


# wget https://github.com/Guutong/pySQLdump/releases/download/v.0.0.1/pySQLdumpSetup.sh

# chmod +x pySQLdumpSetup.sh

# mkdir /root/pySQLBackup/

# ./pySQLdumpSetup.sh


Set vi conf/settings.ini

[mysql]
user = user_name
password = pass_word
dbname = db_name
destination = /root/pySQLBackup/

How to setting Auto backup with crontab

sudo apt-get install crontab
crontab -e
00 00 * * 0 cd /opt/pySQLdump/ && sh run.sh
ESC
:wq!
/etc/init.d/cron restart 
Code Python
#!/usr/bin/python
######################################################
#____________________________________________________#
#_______________Mr.Pornmongkon Pongsai_______________#
#____________________pySQLdump v.0.1_________________#
#______________Create Date : 25-07-2015______________#
#____________________________________________________#
######################################################
from ConfigParser import SafeConfigParser
from os import path
from subprocess import Popen, PIPE
import shlex
import datetime
import logging

def main():
    config_file = 'conf/settings.ini'
    logs_path = 'logs/pySQLdump.log'
    logging.basicConfig(filename=logs_path,format='%(asctime)s:%(levelname)s:%(message)s',level=logging.DEBUG)
    # Read in all the settings
    config = SafeConfigParser()
    config.read(config_file)
    user = config.get('mysql', 'user')
    password = config.get('mysql', 'password')
    database = config.get('mysql', 'dbname')
    destination = config.get('mysql', 'destination')
    date = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    file_name = 'pySQLdump-' + database + '-' + date

    logging.info('==[RUN]== Running mysqldump')
    cmd = 'mysqldump -u' + user + ' ' + database + ' -p"' + password + '" --result-file="' + file_name + '.sql"'
    logging.debug(cmd) 
    run_cmd(cmd)

    logging.info('Creating Zip file')
    run_cmd('zip ' + file_name + '.zip ' + file_name + '.sql')

    logging.info('Removing dump file')
    run_cmd('rm ' + file_name + '.sql')

    logging.info('Moving zipped tarball to destination')
    run_cmd('mv ' + file_name + '.zip ' + destination)
    logging.info('==[PASS]== Mysqldump success!')
    
def run_cmd(cmd):
    process = Popen(shlex.split(cmd), stdout=PIPE)
    dump_output = process.communicate()[0]
    exit_code = process.wait()
    if exit_code != 0:
        print(dump_output)
        raise Exception(str(exit_code) + ' - Error executing command.  Please review output.')

if __name__ == '__main__':
    main()

วันอาทิตย์ที่ 14 มิถุนายน พ.ศ. 2558

[HOW TO] LINE Bot on Raspberry PI with LINE API Python

[HOW TO] LINE Bot on Raspberry PI with LINE API Python   

1. ทำการอัพเดท packet ของ raspbian ก่อน
sudo apt-get install update
sudo apt-get install upgrade
 2. ซึ่ง [LINE API Python] จำเป็นต้องลง packet python 
sudo apt-get install python
sudo apt-get install python-pip
3. ทำการ download [LINE API Python] จาก https://github.com/carpedm20/LINE ในนี้จะมีทั้งวิธีใช้ด้วย
wget https://github.com/carpedm20/LINE/archive/master.zip
unzip master.zip
cd LINE-master/
4. ทำการแก้ไข ไฟล์ api.py ให้สามารถเชื่อมต่อกับ server หลักได้
ทำการเพิ่ม สคริป ภายใต้
def ready(self):
  """
  After login, make `client` and `client_in` instance
  to communicate with LINE server
  """
เอาเครื่องหมาย + ออกด้วย
+        self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL)
 +        self.transport_in = THttpClient.THttpClient(self.LINE_HTTP_IN_URL)
 +        self.transport.setCustomHeaders(self._headers)
 +        self.transport_in.setCustomHeaders(self._headers)
 +        self.protocol = TCompactProtocol.TCompactProtocol(self.transport)
 +        self.protocol_in = TCompactProtocol.TCompactProtocol(self.transport_in)
 +        self._client = CurveThrift.Client(self.protocol)
 +        self._client_in = CurveThrift.Client(self.protocol_in)
 +        self.transport.open()
 +        self.transport_in.open()

5. ทำการรันไฟล์ config.py และ ติดตั้งด้วย setup.py
python config.py
python setup.py install

6. หากไม่มี Error  ใดๆในการติดตั้ง ให้ทดลองการส่งข้อความด้วยไฟล์ echobot.py ใน examples (อย่าลืมเข้าไปแก้ไฟล์ โดยการใส่ ID และ Pass ด้วยนะครับ)
vi echobot.py



เพิ่มเติม script checks status
vi check.py
import subprocess
from line import LineClient, LineGroup, LineContact

try:
    client = LineClient("ID", "PASS")
    #client = LineClient(authToken="TOKEN")
except:
    print "Login Failed"

while True:
    op_list = []

    for op in client.longPoll():
        op_list.append(op)

    for op in op_list:
        sender   = op[0]
        receiver = op[1]
        message  = op[2]

        msg = message.text
        if 'GetRAM' in msg:
                proc=subprocess.Popen('egrep --color "Mem|Cache|Swap" /proc/meminfo', shell=True, stdout=subprocess.PIPE, )
                output=proc.communicate()[0]
                sender.sendMessage("[%s] %s" % (sender.name, output))

        if 'GetDATE' in msg:
                proc=subprocess.Popen('date', shell=True, stdout=subprocess.PIPE, )
                output=proc.communicate()[0]
                sender.sendMessage("[%s] %s" % (sender.name, output))

        if 'GetKERNAL' in msg:
                proc=subprocess.Popen('uname -a', shell=True, stdout=subprocess.PIPE, )
                output=proc.communicate()[0]
                sender.sendMessage("[%s] %s" % (sender.name, output))


ขอบคุณ Api ดีๆจาก https://github.com/carpedm20/LINE
เครดิต : ตาเล็ก วินโด้

วันอังคารที่ 28 เมษายน พ.ศ. 2558

[HOW TO] Generate word ด้วย Python script

Generate word ด้วย Python script(หัดทำ)
วิธีรัน 
1.เข้า Terminal ด้วยสิทธิ์ Root
2.เมื่อสร้างไฟล์เสร็จให้ทำการเปลี่ยนไฟล์ให้ execute ได้ ด้วย
chmod +x genword.py
3. รันด้วยคำสั่ง 
./genword.py -f <fileName.txt> -n <line Of Number> -w <word Generate>



#!/usr/bin/python
######################################################
#____________________________________________________#
#_______________Mr.Pornmongkon Pongsai_______________#
#________________Computer Engineering________________#
#_____________Generate Word for Project______________#
#____________Create Date : 28 April 2015_____________#
#____________________________________________________#
######################################################
import sys
import getopt

def main(argv):
 fileName = 'default'
 lineNumber = 0
 wordGen = 'default'
 try:
  opts, args = getopt.getopt(argv,"hf:n:w:",["file=","number=","word="])
 except getopt.GetoptError:
  print 'Help : genword.py -f  -n  -w '
  sys.exit(2)
 for opt, arg in opts:
  if opt == '-h':
   print 'Help : genword.py -f  -n  -w '
   sys.exit()
  elif opt in ("-f", "--file"):
   fileName = arg
  elif opt in ("-n", "--number"):
   lineNumber = int(arg)
  elif opt in ("-w", "--word"):
   wordGen = arg  
 print '[log] : generate word start!'
 dataFile = open(fileName, 'w')
 i = 0
 while ( i < lineNumber ):
  dataFile.write(wordGen+'\n')
  i = i + 1
 dataFile.close()
 print '[log] : generate word finish!'
if __name__ == "__main__":
 print '######################################################'
 print '#____________________________________________________#'
 print '#_______________Mr.Pornmongkon Pongsai_______________#'
 print '#________________Computer Engineering________________#'
 print '#_____________Generate Word for Project______________#'
 print '#____________Create Date : 28 April 2015_____________#'
 print '#____________________________________________________#'
 print '######################################################'
 print '!!!-h for help!!!'
 main(sys.argv[1:])

วันพุธที่ 15 เมษายน พ.ศ. 2558

[HOW TO] Check status service linux with Python

เช็คสถานะ service linux ด้วย Python(หัดทำ)
    

     เพื่อเวลาที่ server ทำงานแล้วเกิดบาง service down เราจะได้ไม่ต้องมานั่ง start stop restart พวก service บ่อยๆ 
วิธีรัน 
1.เข้า Terminal ด้วยสิทธิ์ Root
2.เมื่อสร้างไฟล์เสร็จให้ทำการเปลี่ยนไฟล์ให้ execute ได้ ด้วย
chmod +x filename.py
3. รันด้วยคำสั่ง 
./filename.py 

#!/usr/bin/python
import commands
import time
import os
while True:
 #find process
        pc = commands.getoutput('ps -aux | grep nginx | grep -v grep').strip()

        if(len(pc) > 0):
                print 'process running. skip'
        else:
  print 'process not running'
                #stop program
                os.system('sudo service nginx stop')
                #start program
         os.system('sudo service nginx start')
  print 'process started'
 #Check every 1 minute
        time.sleep(1 * 60)