PHP простые примеры и тесты кода
#!/usr/local/bin/python import datetime import os PREFIX = "/usr/backup/MySQL/" dt = datetime.datetime.now() date = "{0}{1:0=2}{2:0=2}".format(dt.year, dt.month, dt.day) filename = PREFIX + date + ".sql" os.system("mysqldump --user root --password=mysqlroot -A > " + filename)
#!/usr/local/bin/python import datetime import os PREFIX = "/usr/backup/" dt = datetime.datetime.now() date = "{0}{1:0=2}{2:0=2}".format(dt.year, dt.month, dt.day) filename = PREFIX + date + ".tar.gz" os.system("tar -czvf " + filename + " /usr/www/")
Необходима php функция mail()
#!/bin/bash DISK="/dev/xvda1" #Ваш диск (доступен через df) MIN_AVAIL_PERCENT=94 #Граница занимаемого места (Если 94 то сработает, только если занятое пространство 95%) if [ $(df -P $DISK | tail -n 1 | grep -o "[0-9]*%" | grep -o "[0-9]*") -gt $MIN_AVAIL_PERCENT ] then /root/send_email_if_dont_have_space.php #Ссылка на скрипт приведенный ниже fi
#!/usr/bin/php <?php $title1 = "Заканчивается место на (таком-то сервере)?"; # Наш заголовок $title = substr(htmlspecialchars(trim($title1)), 0, 1000); $mess1 = "Добрый день. Проверьте пожалуйста место на (таком-то сервере), для этого зайдите на сервер по ssh и введите команду df -h"; #Наше сообщение $mess = substr(htmlspecialchars(trim($mess1)), 0, 1000000); $to = 'target@email.ru'; #Наш email mail($to, $title, $mess); ?>
И прописываем это в crontab
Наш файлик
#!/bin/bash STRING=/root/test/$(date +Day%d-Hour%H-Min%M) ps aux >> $STRING
И кидаем его в crontab на выполнение.
#!/bin/bash echo -e "\n==== Current memory usage ====\n" echo -e "SIZE(Mb) \t NUM \t NAME" echo -e "-------- \t --- \t ----\n" echo "" > ./testtmp proc_name=`ps -A --sort -rss -o pid,comm,pmem,rss | awk '{print $2}' | sort | uniq` for proc in $proc_name; do ps -A --sort -rss -o pid,comm,pmem,rss | grep $proc | awk '{sum=sum+$4; num++} END {printf("%.2f \t\t %d \t %s", sum/1024, num, $2)}' | awk '{if($1>0){print}}' >> testtmp done all_mem=`free -m | grep Mem | awk '{print $2}'` cat testtmp | sort -rn | awk '{sum=sum+$1; print}; END {print "Total Used: "sum" Mb\nTotal Free: "'$all_mem'-sum" Mb"}' echo -e "\n\n\n==== Current swap usage ====\n" echo -e "SIZE(kB) \t PID \t NAME" echo -e "-------- \t --- \t ----" echo "" > testtmp for x in `find /proc/ -maxdepth 2 -name 'smaps' -exec ls -la {} \; | awk '{print $9}'`; do if [ -f $x ]; then y=`cat $x | awk '{if($1=="Swap:" ){ sum=sum+$2 } }; END {print sum}'` t=`echo $x | awk -F/ '{print $3}'` z=`ps -A --sort -rss -o pid,comm | awk "{ if(\\$1==$t) {print \\$2} }"` echo -e $y"\t\t"$t"\t"$z | awk '{if($1>0 && $3!="" ){print}}' >> testtmp fi done all_swap=`free -m | grep Swap | awk '{print $2}'` cat testtmp | awk '{sum=sum+$1; print}; END {print "\nTotal Used: "sum/1024" Mb\nTotal Free: "'$all_swap'-sum/1024" Mb\n\n"}' echo "" > testtmp
Вывод:
==== Current memory usage ==== SIZE(Mb) NUM NAME -------- --- ---- 618.82 13 chromium-browse 300.09 1 thunderbird 136.40 1 Xorg 130.14 11 apache2 105.39 1 guake 97.70 41 flush-252:0 60.00 19 bash 46.71 1 nagstamon Total Used: 2356.87 Mb Total Free: 5299.13 Mb ==== Current swap usage ==== SIZE(kB) PID NAME -------- --- ---- Total Used: 0 Mb Total Free: 8135 Mb
#!/bin/bash #apt-get install scrot #Delete files after 30 days WD=/home/sysadmin/screens export DISPLAY=:0 [ ! -d $WD ] && mkdir -p $WD /usr/bin/scrot $WD/sc-$(date '+%Y-%m-%d_%H:%M').png >> /tmp/scrot.log 2>&1 if [ `date '+%H'` -eq 19 ]; then # removing old screenshots cd /tmp find $WD -mtime +30 | xargs -r rm fi
import MySQLdb import threading import time import traceback import sys howManyThreads = 200 SQL_host = '11.11.11.11' SQL_user = 'user' SQL_pass = 'pass' SQL_base = 'base' class myThread (threading.Thread): def __init__(self, id): threading.Thread.__init__(self) self.id = id self.conn = "" def run(self): while(1): try: self.execution() except: print("Some Error:") traceback.print_exc(file=sys.stdout) print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") def execution(self): self.conn = MySQLdb.connect (SQL_host, SQL_user, SQL_pass, SQL_base) self.cursor = self.conn.cursor () self.cursor.execute ("SELECT * FROM emails") # self.cursor.execute ("SELECT VERSION()") self.row = self.cursor.fetchone() print(self.row, self.id) threads = [] for id in range(howManyThreads): thread = myThread(id) thread.start() threads.append(thread)
#Python 3.2 (r32:88445, Dec 8 2011, 15:26:51) [GCC 4.5.2] on linux2 # TODO - Create "SelfExtractor()" and deleted "try" # TODO - RestoreConnect() his return -11 if bad and 1 if good. Use RestoreConnect, if some bad #ConConovaloff do it import MySQLdb import threading import time import traceback import sys import os import io import signal Debug = 1 if Debug == 1 : print("| Show Time") ######## Configure SQL_host = '11.11.11.11' SQL_user = 'user' SQL_pass = 'pass' SQL_base = 'base' Log_path = "/usr/log/mysql" ####### Thread MySignal = "" ErrorMassageBuf = io.StringIO() startTime = time.time() KillingFlag = 0 if Debug == 1 : print("| Before MySQL_Pthread") class MySQL_Pthread (threading.Thread): if Debug == 1 : print("| In MySQL_Pthread") global MySignal global ErrorMassageBuf def __init__(self): threading.Thread.__init__(self) if Debug == 1 : print("| In MySQL_Pthread -> init") signal.signal(signal.SIGUSR1 , self.usrsignal) # IF need killing proc in mysql, use kill -SIGUSR1 $PID self.conn = MySQLdb.connect (SQL_host, SQL_user, SQL_pass, SQL_base) self.cursor = self.conn.cursor () def run(self): if Debug == 1 : print("| In MySQL_Pthread -> run") global MySignal global ErrorMassageBuf while(1): if Debug == 1 : print("| In MySQL_Pthread -> run -> While +1") if MySignal != "" : if Debug == 1 : print("| In MySQL_Pthread -> run -> While -> Some Find") ### Generate log file MyDay = time.strftime("%d.%b", time.localtime()) MyTime = time.strftime("%H:%M:%S", time.localtime()) path = Log_path + "/" + MyDay + "/" + SQL_host + "_" + MyTime dirPath = os.path.dirname(path) FileName = os.path.basename(path) if not os.path.exists(dirPath): if Debug == 1 : print("| In MySQL_Pthread -> run -> While -> Some Find -> CreateDir") os.makedirs(dirPath, 0o777 , True) if Debug == 1 : print("| In MySQL_Pthread -> run -> While -> Some Find -> CreateFile") self.LogFile = open(path, mode='a') ### if self.execution(MySignal, True) == -11 : continue if Debug == 1 : print("| In MySQL_Pthread -> run -> While -> Some Find -> ClearMySignal") MySignal = "" if self.execution() == -11 : continue print("%s: %s MinUpTime: %i" % ("Time", time.ctime(time.time()), (time.time() - startTime)/60)) time.sleep(12) TestTread = MySQL_Tthread() TestTread.start() time.sleep(3) def execution(self, code = "SELECT VERSION()", alarm = False): global ErrorMassageBuf global KillingFlag if Debug == 1 or alarm : print("| In MySQL_Pthread -> execution:", code) try: self.cursor.execute(code) except: if Debug == 1 : print("| In MySQL_Pthread -> execution -> SomeBad: return -11 and restart") self.conn = MySQLdb.connect (SQL_host, SQL_user, SQL_pass, SQL_base) self.cursor = self.conn.cursor() return -11 self.row = self.cursor.fetchall() for self.line in self.row: print("Pthread:", self.line) if alarm : if Debug == 1 : print("| In MySQL_Pthread -> execution -> Alarm -> Write log file") self.LogFile.write(str(ErrorMassageBuf.getvalue()) + "\n") for self.line in self.row: self.LogFile.write(str(self.line) + "\n") self.LogFile.close() if Debug == 1 : print("| In MySQL_Pthread -> execution -> Alarm -> Write log file, Done") if KillingFlag == 1 : self.killing_proc() KillingFlag = 0 def killing_proc(self): if Debug == 1 : print("| In MySQL_Pthread -> killing_proc") #Получить id нашего постоянного подключения и убить всех, кроме нас. try: self.cursor.execute("show full processlist") except: if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> SomeBad: return -11 and restart") self.conn = MySQLdb.connect (SQL_host, SQL_user, SQL_pass, SQL_base) self.cursor = self.conn.cursor() return -11 rowList = self.cursor.fetchall() #(2740, 'konovalovv', '95-27-202-166.broadband.corbina.ru:48770', 'paprica', 'Query', 170, 'Writing to net', 'SELECT * FROM emails') for line in rowList: if "show full processlist" in line: if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> Don't kill self: id", line) continue elif "root" in line[1]: if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> Don't kill root: id", line) continue else: if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> kill", line[0]) try: self.cursor.execute("KILL "+ str(line[0])) except: if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> Not killing", line[0]) pass if Debug == 1 : print("| In MySQL_Pthread -> killing_proc -> work done") def usrsignal(self, signum, frame): if Debug == 1 : print("| In MySQL_Pthread -> Get Singal to allow kill") global KillingFlag KillingFlag = 1 if Debug == 1 : print("| Before MySQL_Tthread") class MySQL_Tthread (threading.Thread): if Debug == 1 : print("| In MySQL_Tthread") global MySignal global ErrorMassageBuf def __init__(self): threading.Thread.__init__(self) if Debug == 1 : print("| In MySQL_Tthread -> init") pass def run(self): if Debug == 1 : print("| In MySQL_Tthread -> run") global MySignal global ErrorMassageBuf try: self.execution() except: print("Some Error:") ErrorMassageBuf = io.StringIO() traceback.print_exc(file=ErrorMassageBuf) print(str(ErrorMassageBuf.getvalue())) print("++++++++++++++++++++++++++++++++++++++++++++++++++++++") MySignal = "show full processlist" def execution(self): if Debug == 1 : print("| In MySQL_Tthread -> execution") self.conn = MySQLdb.connect (SQL_host, SQL_user, SQL_pass, SQL_base) self.cursor = self.conn.cursor() self.cursor.execute ("SELECT VERSION()") self.row = self.cursor.fetchone() print("Tthread server version:", self.row) self.cursor.close() self.conn.close() if Debug == 1 : print("| In MySQL_Tthread -> execution -> close connect") if Debug == 1 : print("| if __name__ == '__main__' ") if __name__ == "__main__" : Mainthread = MySQL_Pthread() Mainthread.start() if Debug == 1 : print("| END if __name__ == '__main__' ") if Debug == 1 : print("| End File ")
#!/usr/bin/python # -*- coding: utf-8 -*- # ConConovaloff do it # Tested on: python3.2
import os import re import sys HelpMessage = """ Проверка регэкспы: cat file | sender.py --find 'regexp' Замена текста в файле по регэкспе: find ./ -type f | xargs -I{} sender.py --changefile {} 'regexp' 'sub' """ if len(sys.argv) > 1: if sys.argv[1] == "--find" or sys.argv[1] == "--test": if len(sys.argv) > 2: Regexp = sys.argv[2] RegexpPattern = re.compile(Regexp, re.DOTALL) Stdin = sys.stdin print(RegexpPattern.findall(Stdin.read())) else: print("Use: cat file | sender.py --find 'regexp'") if sys.argv[1] == "--changefile": if len(sys.argv) == 5: RegexpPattern = re.compile(sys.argv[3], re.DOTALL) MySub = sys.argv[4] print('Change file:', sys.argv[2]) rfile = open(sys.argv[2], 'r') text = rfile.read() rfile.close() text = RegexpPattern.sub(MySub, text) wfile = open(sys.argv[2], 'w') wfile.write(text) wfile.close() else: print("""Use: find ./ -type f | xargs -I{} sender.py --changefile {} 'regexp' 'sub'""") else: print(HelpMessage) else: print(HelpMessage)
#!/bin/bash #ConConovaloff do it LOGPATH="/root/bash/log" COUNT=8 HOUR=1 # Exit if less $COUNT in $HOUR function needSend(){ for i in $(tail -n$COUNT $LOGPATH/`date +%m-%Y` | awk '{print $1}'); do SECOND=$(echo "$i + (3600 * $HOUR) - `date +%s`" | bc) echo $SECOND if [ "$SECOND" -lt 0 ]; then echo less 0 #Отправить sms return 0 # 0 for true fi done #Не отправлять sms return 1 } if needSend ; then echo `date +%s" "%F` success >> $LOGPATH/`date +%m-%Y` echo SendSMS fi
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- #ConConovaloff do it #Example use: #import googleTranslate #googleApi = googleTranslate.connector("APIKEYooooooooooSDLJFasdfsdlfzbo") #print(googleApi.translate("Чудесное утро")) from urllib import pathname2url from httplib import HTTPSConnection import re translate_pattern = re.compile('\"translatedText\": \"(.*?)\"') class connector: def __init__(self, apiKey): self.apiKey = apiKey self.lang = "en" self.host = "www.googleapis.com" self.port = 443 self.data = "key=" + self.apiKey + "&source=ru&target=" self.conn = HTTPSConnection(self.host, self.port) self.header = {"Content-type": "application/x-www-form-urlencoded", "X-HTTP-Method-Override": "GET"} def translate(self, text): queryString = self.data + self.lang + "&q=" + pathname2url(text) queryLen = len(queryString) self.conn.request("POST", "/language/translate/v2", "", dict(self.header.items() + [("Content-Length", queryLen)])) self.conn.send(queryString) response = self.conn.getresponse() queryAnswer = response.read() return translate_pattern.findall(queryAnswer)[0] def changeLang(self, lang): self.lang = lang if __name__ == '__main__': con = connector("APIKEYooooAIzsdlafklSDFSDFLJSFsdfDzbo") print(con.translate("Чудесное утро"))
icon_urls = [ "/img/info_92.png" "http://icons.iconarchive.com/icons/kyo-tux/phuzion/256/Sign-Info-icon.png" "http://konovalov.cp.beget.ru/img/menu/280/feedback.png" "http://icons.iconarchive.com/icons/visualpharm/must-have/256/Information-icon.png" "http://www.archeryeurope.org/images/images/info-icon.ico" "http://upload.wikimedia.org/wikipedia/commons/4/47/Simple_Information.svg" "http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons-256/blue-jelly-icons-alphanumeric/069499-blue-jelly-icon-alphanumeric-information.png" "http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons-256/blue-chrome-rain-icons-alphanumeric/069351-blue-chrome-rain-icon-alphanumeric-information.png" "http://img2.wikia.nocookie.net/__cb20100821004400/sims/images/c/ca/Info_information_icon.png" "https://www.rjschinner.com/images/site/info-icon.png" "http://img3.wikia.nocookie.net/__cb20110802222747/onepiece/images/7/77/Info-icon.svg" "http://icons.iconarchive.com/icons/rade8/minium-2/256/General-Get-Info-icon.png" "http://upload.wikimedia.org/wikipedia/commons/thumb/3/33/Info_icon_002.svg/480px-Info_icon_002.svg.png" "http://icons.iconarchive.com/icons/custom-icon-design/office/256/info-icon.png" "http://muiscientific.com/wp-content/uploads/2013/11/info.png" "http://media.merchantcircle.com/29977176/MSN%20icon%20info%20bubble_full.png" "http://icons.iconarchive.com/icons/tpdkdesign.net/refresh-cl/256/Symbols-Info-icon.png" "http://c.dryicons.com/images/icon_sets/colorful_stickers_icons_set/png/256x256/info.png" "https://cdn1.iconfinder.com/data/icons/meBaze-Freebies/512/info-blog.png" "http://www.datastorm-solutions.com/images/icon_info.png" "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Cute-Ball-Info-icon.png" "http://www.veryicon.com/icon/ico/System/Crystal%20Clear%20Actions/Info.ico" "http://img2.wikia.nocookie.net/__cb20101117192950/halo/de/images/5/58/Info_icon.png" "http://grosvenoraircraft.co.uk/images/icon_info.jpg" "http://cdn.researcher.poly.edu/images/libguides/ICONS/more_information_icon.jpg" "https://cdn1.iconfinder.com/data/icons/perfect-flat-icons-2/512/Info_information_user_about_card_button_symbol.png" "https://partners.myskanska.com/usa/clients/UP/Coltonflyover/Website%20Files/Information_icon%20SP%20ver%202.png" "http://t1.ftcdn.net/jpg/00/01/49/34/400_F_1493418_NUtI2GnfXZ4JKMrk7LrEF80Fl8skcz.jpg" "http://osa.fizyka.umk.pl/OPTO_2013/img/informations/information.png" "http://etc-mysitemyway.s3.amazonaws.com/icons/legacy-previews/icons/simple-red-square-icons-signs/129584-simple-red-square-icon-signs-z-roadsign75.png" # "http://icons-search.com/img/icons-land/IconsLandVistaElementsIconsDemo.zip/IconsLandVistaElementsIconsDemo-PNG-256x256-InfoBox.png-256x256.png" ] icon_marker = 0 images_compare = [] images_compare_marker = 0 images_pre = [] preload = (arg) -> for image, i in arg images_pre[i] = new Image() images_pre[i].src = image preload(icon_urls) changeIco = (num) -> icon_marker = icon_marker + num icon_marker = icon_urls.length - 1 if icon_marker < 0 icon_marker = 0 if not icon_urls[icon_marker]? console.log(icon_urls[icon_marker]) $(".dialog_container").css("background-image", "url(" + icon_urls[icon_marker] + ")") changeIcoCompare = (num) -> images_compare_marker = images_compare_marker + num images_compare_marker = images_compare.length - 1 if images_compare_marker < 0 images_compare_marker = 0 if not images_compare[images_compare_marker]? console.log images_compare[images_compare_marker] $(".dialog_container").css("background-image", "url(" + images_compare[images_compare_marker] + ")") addToCompare = () -> url = $(".dialog_container").last().css("background-image").slice(4, -1) images_compare.push(url) $(document).keydown (e) -> changeIco(+1) if e.keyCode is 39 #right changeIco(-1) if e.keyCode is 37 #left changeIcoCompare(+1) if e.keyCode is 38 #up changeIcoCompare(-1) if e.keyCode is 40 #down addToCompare() if e.keyCode is 32 #space
#!/usr/bin/php <?php if (count($argv) < 2) { exit("Not name\n"); } if (preg_match('/[а-я]/ui', $argv[1])) { exit(idn_to_ascii($argv[1]) . PHP_EOL); } exit(idn_to_utf8($argv[1]) . PHP_EOL);
Discussion
kono_read_without_comment
kono_grep
kono_fix_right
kono_logs
kono_grep_first
kono_grep_next
kono_git_rebase_by_patch
kono_git_merge_master
kono_xdebug
включаем\выключаем xddebug с рестартом сервера. А то очень много ресурсов отжирает xdebug (в phpstorm при этом постоянно включен)
OLD: