Tampilkan postingan dengan label Python. Tampilkan semua postingan
Tampilkan postingan dengan label Python. Tampilkan semua postingan

How To Check MySQL Was Running With Python Script

How To Check MySQL Was Running With Python Script
Sering pertanyaan kita hinggap dipikiran kita, semakin dipikirkan semakin gak ngerti seringnya, apalagi sesuatu yang gak kliatan kerjanya seperti master kita satu ini MySQL Database. Awalnya ini script digunakan untuk keperluan deteksi pakah mysql jalan atao kagak, Kalo mysqlnya gak jalan tinggal dikasih script buat jalanin si doi, jadi kalo misalnya ada aplikasi yang mau masukin n baca data tinggal cek dulu apa mysql ini jalan ato kagak. 

Aplikasi yang baru dikembangin kebetulan pake python n jalan di Raspberry Pi Rev B, dan rencanya ini nanti dikasih di crontab nya cron buat di cek setiap menit untuk memastikan database jalan dengan sempurna, karena ane juga gak ngerti script python mungkin sering juga gua browse sana sini, eee gua nemu juga di internet script ajaib ini.

Manfaatin subprocess yang ada di Python langsung memberikan perintah melalui shell/terminal. Di raspberry penggunaan perintah ini gak perlu pake memasukkan pasword dari sudo yang dilakukan kalo memang dibutuhkan untuk menjalakn proses dengan authorisasi Super user.

Cara paling mudah untuk membuat ini bekerja adalah sebagai berikut

Script :

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."


Yang dibawah ini mungkin agak berbeda, kalo kalian ingin mereset MySQL jalankan peritah berikut dengan cript python :

Shell script to restart MySQL server if it is killed or not workin

    #!/bin/bash # Shell script to restart MySQL server if it is killed or not working # due to ANY causes. # When script detects mysql is not running (it basically sends ping request # to MySQL) it try to start using /etc/init.d/mysql script; and it sends an # email to user indicating the status. # This script must be run from Cron Job so that it can monitor mysql server. # For more info visit following url: # http://www.cyberciti.biz/nixcraft/vivek/blogger/2005/08/linux-mysql-server-monitoring.html # -------------------------------------------------------------------------- # Copyright (C) 2005 nixCraft project # This script is licensed under GNU GPL version 2.0 or above # ------------------------------------------------------------------------- # This script is part of nixCraft shell script collection (NSSC) # Visit http://bash.cyberciti.biz/ for more information. # ------------------------------------------------------------------------- # mysql root/admin username MUSER="root" # mysql admin/root password MPASS="SET-ROOT-PASSWORD" # mysql server hostname MHOST="localhost" #Shell script to start MySQL server i.e. path to MySQL daemon start/stop script. # Debain uses following script, need to setup this according to your UNIX/Linux/BSD OS. MSTART="/etc/init.d/mysql start" # Email ID to send notification EMAILID="notification@somewhere-corp.com" # path to mail program MAILCMD="$(which mail)" # path mysqladmin MADMIN="$(which mysqladmin)" #### DO NOT CHANGE anything BELOW #### MAILMESSAGE="/tmp/mysql.fail.$$" # see if MySQL server is alive or not # 2&1 could be better but i would like to keep it simple and easy to # understand stuff :) $MADMIN -h $MHOST -u $MUSER -p${MPASS} ping 2>/dev/null 1>/dev/null if [ $? -ne 0 ]; then echo "" >$MAILMESSAGE echo "Error: MySQL Server is not running/responding ping request">>$MAILMESSAGE echo "Hostname: $(hostname)" >>$MAILMESSAGE echo "Date & Time: $(date)" >>$MAILMESSAGE # try to start mysql $MSTART>/dev/null # see if it is started or not o=$(ps cax | grep -c ' mysqld$') if [ $o -eq 1 ]; then sMess="MySQL Server MySQL server successfully restarted" else sMess="MySQL server FAILED to restart" fi # Email status too echo "Current Status: $sMess" >>$MAILMESSAGE echo "" >>$MAILMESSAGE echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE # send email $MAILCMD -s "MySQL server" $EMAILID < $MAILMESSAGE else # MySQL is running :) and do nothing : fi # remove file rm -f $MAILMESSAGE
Sekian cerita ane ntar nyambung lagi...

Connection To Microsoft SQL Server Database From Python

Connection To Microsoft SQL Server Database From Python

Free tools are great, but the world ain't all sunshine and rainbows. Sometimes, we may need to connect to a Microsoft SQL Server database from one of our Python applications running under Linux. Fortunately, there are ways to achieve this.
I am assuming we got this:
  • • A Microsoft SQL Server installation running under Windows. I tested this using Microsoft SQL Server 2008 R2 Express, but hopefully this will work with other versions as well.
  • • Ubuntu Linux. I am using 12.04 LTS.
Without further ado, here are the steps you should follow to get this working.

1. SQL Server setup

Your SQL Server installation must be setup to allow external connections. If the DB is not administered by you this might not be a problem, but in case you do have administrator level access and need to do it yourself, read here.
Now you must have setup a port in which SQL Server is listening. Remember it.
Make sure you are not blocked by Windows firewall or such when you attempt to connect to the Windows computer. Attempting a telnet will help us check if there are connection problems. For example, try running telnet from Ubuntu and check the connection doesn't fail.
Regarding authentication, I have only tried this with the sa login enabled (ie. not using Windows Authentication). You may read on how to do that here.

2. Install required packages under Ubuntu

These are the things we are going to need:
  • • FreeTDS is is a set of libraries that allows programs to natively talk to Microsoft SQL Server databases. It's what we usually call a driver.
  • • UnixODBC acts as a driver manager and is the implementation of the ODBC API.
  • • pyodbc is a Python 2.x and 3.x module that allows you to use ODBC to connect to almost any database.
From a terminal, run:
sudo apt-get install unixodbc unixodbc-dev freetds-dev tdsodbc
From the Virtualenv of our Python application (if you are not using one, you should!) run pip install pyodbc.

3. Setup server in FreeTDS's settings

Edit the file /etc/freetds/freetds.conf and replace placeholders appropriately. Note that we are calling our server sqlserver.
[sqlserver]
    host = 
    port = 
    tds version = 7.0
After this you can test the connection with this command:
tsql -S sqlserver -U  -P 
note : tsql not build in freetds, you can add with apt-get install freetds-bin

Then run some SQL Server command to make sure everything works fine. For example you may run a DB query like this:
select * from .dbo.
go
If it worked, it will print the results of the query. Quit with Ctrl+D.

4. Setup unixODBC to use FreeTSD & add a data source

First, run odbcinst -j to know where our configuration files are located. We will need to edit two files: the "drivers" and "system data source". I assume they are /etc/odbcinst.ini and /etc/odbc.ini respectively, but the output of the command will tell you this.

Edit /etc/odbcinst.ini like this:
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
# Some installations may differ in the paths
#Driver = /usr/lib/odbc/libtdsodbc.so
#Setup = /usr/lib/odbc/libtdsS.so
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout =
CPReuse =
FileUsage = 1
If the paths for Driver and Setup do not work in your installation, you can find where these files are located by running find / -name "libtds*".
Edit /etc/odbc.ini like this, to add a data source named sqlserverdatasource:
[sqlserverdatasource]
Driver = FreeTDS
Description = ODBC connection via FreeTDS
Trace = No
Servername = sqlserver
Database = 
Now you may test the connection to out data source works by running isql -v sqlserverdatasource .

5. Connect to our data source from a Python application

If everything is fine, with the help of pyodbc it should be really easy! You may try the following snippet:
import pyodbc
dsn = 'sqlserverdatasource'
user = ''
password = ''
database = ''
con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
cnxn = pyodbc.connect(con_string)


That should be it :-)

ref : http://www.tryolabs.com/Blog/2012/06/25/connecting-sql-server-database-python-under-ubuntu/

10 Basic For Newbee in Python

We all know that Python is one of the most sought after programming language in the open source space. It is one language that lets you work very quickly and integrate your system more effectively. So, if you have just stepped into Python, we bring to you ten essential Python tips that will help ease out your journey in this world.

1. Running Python scripts

On major of the UNIX systems, you can run Python scripts from the command line using folowing command.

$ python mypyprog.py

2. Running Python programs from Python interpreter

The Python interactive interpreter is used interchangeable with Python shell. This is where the Python commands can be typed and executed. This makes it easy to try your first steps in programming and using all Python commands. You just issue each command at the command prompt, one by one, and the answer is immediate.

Python interpreter can be started by issuing the command:

$ python
atithya@ubuntu:~$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

In this article, all the code starting with the >>> symbol are meant to be given at the Python prompt. It is also important to remember that Python takes tabs very seriously – so if you are receiving any error that mentions tabs, correct the tab spacing.

3. Dynamic typing

In Java, C++, and other statically typed languages, you must specify the data type of the function return value and each function argument. On the other hand, Python is a dynamically typed language. In Python, you never have to explicitly specify the data type of anything. Based on what value you assign, Python will keep track of the data type internally.

4. Python statements

Python uses carriage returns to separate statements, and a colon and indentation to separate code blocks. Most of the compiled programming languages, such as C and C++, use semicolons to separate statements and curly brackets to separate code blocks.

5. == and = operators

Python uses ‘==’ for comparison and ‘=’ for assignment. Python does not support inline assignment, so there’s no chance of accidentally assigning the value when you actually want to compare it.

Today, Python is one of the most popular programming languages in the open source space. It’s a vast language and there are many gems to discover – here are ten tips for new users to get the ball rolling…

6. Concatenating strings

You can use ‘+’ to concatenate strings like so:

>>> print 'atit'+'hya'
atithya

7. The __init__ method

The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. The __init__ method is analogous to a constructor in C++, C# or Java.

[Example]
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print ‘Hello, my name is’, self.name
p = Person(‘Atithya’)
p.sayHi()

[Output]
[~/src/python $:] python initmethod.py
Hello, my name is Atithya

8. Modules

To keep your programs manageable as they grow in size, you may want to break them up into several files. Python allows you to put multiple function definitions into a file and use them as a module that can be imported into other scripts and programs. These files must have a .py extension.

[Example]
# file my_function.py
def minmax(a,b):
if a <= b:
min, max = a, b
else:
min, max = b, a
return min, max
Module Usage
import my_function
x,y = my_function.minmax(25, 6.3)

9. Module defined names

The built-in function ‘dir()’ can be used to find out which names a module defines. It returns a sorted list of strings.

[Example]
>>> import time
>>> dir(time)
[‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘accept2dyear’, ‘altzone’, ‘asctime’, ‘clock’, ‘ctime’, ‘daylight’, ‘gmtime’, ‘localtime’, ‘mktime’, ‘sleep’, ‘strftime’, ‘strptime’, ‘struct_time’, ‘time’, ‘timezone’, ‘tzname’, ‘tzset’]

10. Module internal documentation

You can see the internal documentation (if available) of a module name by looking at .__doc__.

[Example]
>>> import time
>>> print time.clock.__doc__
clock() -> floating point number

This example returns the CPU time or real time since the start of the process or since the first call to clock(). This has as much precision as the system records.

Courtesy: Linuxuser

Kenapa Start Up harus tahu Pemrograman Phyton

Anda ingin ide bisnis Anda berkecambah menjadi teknologi tinggi start- up . Untuk itu , Anda harus membangun sebuah IT solusi / layanan untuk menendang memulai bisnis Anda , baik itu website, solusi perangkat lunak , jaringan sosial , atau aplikasi mobile. Dan Anda harus berpikir keras tentang bahasa untuk memilih untuk menulis produk IT tersebut .

Nah! Anda dapat menulis produk hebat dalam bahasa apapun dan pengguna ketika melihat itu benar-benar tidak dapat memahami bahasa yang digunakan untuk menciptakannya , atau berapa banyak coding butuh . Namun bagi Anda , waktu dan anggaran yang penting untuk membuat start- up fungsional dan tentu saja pilihan bahasa pemrograman menentukan keberhasilan atau kegagalan proyek impian Anda . Menurut opensource.com , berikut adalah beberapa poin untuk memikirkan .

  • Startup Spesifikasi : Start- Ups di awal biasanya berjuang dengan keuangan . Dengan investasi minimum , Python adalah pilihan yang paling populer . Juga , start-up tidak memiliki banyak waktu untuk meyakinkan mitra dan investor tentang potensi proyek . Produk ini harus mulai bekerja segera untuk bertahan hidup dan menghasilkan uang . Dan , akhirnya , start-up selalu usaha yang kompleks.
  • Proyek Complex: Khas start- up seperti proyek media streaming atau jaringan sosial berbasis web . Web , di sisi lain , didorong oleh data yang besar , baik itu video streaming atau jaringan sosial . Python dapat mengatasi kompleksitas ini dan sangat ideal untuk solusi web . Mengintegrasikan dua sistem membutuhkan usaha besar, tapi kesederhanaan filosofi Python membantu . Bahasa juga skor pada skalabilitas .
  • Bukti Konsep dan Kerja Prototip : Python menawarkan solusi siap untuk proyek-proyek besar karena lebih mudah untuk menulis di Python dan menulis ulang nanti dalam bahasa lain , jika diperlukan . Hal ini memberikan waktu start- up . Python adalah bahasa yang sangat baik untuk menulis prototipe dan tidak memerlukan banyak waktu . Dengan prototipe kerja sudah ada, bahasa pemrograman lain bisa, bagaimanapun , membutuhkan waktu. Melalui prototipe , mudah untuk melihat apakah ide bisnis akan bekerja atau tidak .
  • Kode Mudah , Tim Kecil : Python adalah bahasa mudah yang memungkinkan programmer untuk menulis bukti dari konsep . Anda tidak perlu tim besar desainer dan pengembang untuk memiliki produk yang solid di tangan Anda . Hal ini memberikan start-up kesempatan untuk mencoba ide-ide yang berbeda dan melihat mereka bekerja .
  • Investasi Mudah : Bila Anda memiliki sistem kerja , semua yang perlu Anda lakukan adalah memperbaiki bug dan kemudian mendapatkan investasi dengan cepat . Start- up adalah apa-apa tanpa investor dan sehingga sangat penting untuk menunjukkan kepada mereka apa produk seperti . Bahkan dengan besar kesenjangan dan online buzz keras , proyek Anda akan azab jika Anda tidak memiliki investor . Jadi , intinya adalah , menghabiskan lebih sedikit dan mendapatkan kembali lebih cepat .
  • Cepat Uang Pertama : Dengan start- up , Anda harus mulai membuat uang cepat , jika proyek tersebut mungkin gagal . Python adalah keringanan cepat dan karenanya kembalinya keuntungan lebih cepat jika Anda mengembangkan dan mendukung Anda start- up di Python . Keuntungan akan lebih besar karena pengeluaran awal lebih rendah .
  • Baik Support Team : Python diciptakan dan didorong oleh penggemar . Dukungan pelanggan yang baik memungkinkan untuk menjadi stabil , kualitas tinggi . Jika Anda memilih dukungan Python , Anda akan menikmati tingkat respon cepat , resolusi cepat masalah teknis , pikiran terbuka dan profesional gairah yang adalah penggemar terbesar dari produk mereka .

Startups harus menghadapi persaingan sengit dan saat mereka bersinar tidak berlangsung selamanya . Python memungkinkan Anda untuk memiliki kerja, produk yang kompleks dalam satu atau dua bulan, dengan hanya satu atau dua orang . Dengan sedikit investasi , Anda bisa mendapatkan bukti dari konsep atau bahkan prototipe kerja langsung ke investor dan mendapatkan dana yang Anda butuhkan. Anda dapat mulai membuat uang sekarang dan membangun reputasi bisnis Anda dengan bantuan dukungan yang sangat baik .