4 Kasım 2013 Pazartesi

Raspberry pi ile otomatik IP adresi öğrenme

Bu uygulama ile raspberry pi üzerinde çalışan ufak bir kod sayesinde ip adresiniz değişse bile öğrenip istediğiniz adrese mail olarak gönderebileceksiniz.

Aşağıdaki kodda: gonderenMailAdresi, password ve aliciMailAdresi bilgilerini dolurun. Ardından "/home/" klasörü altına getIP.py olarak kopyalayın.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import re
import smtplib  
import time
import sys
  
def getIP():
 url = "http://checkip.dyndns.org"
 print "IP Addresi alınıyor"
  
 print url
  
 request = urllib.urlopen(url).read()
 global theIP   
 theIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
 global eskiIpAdresi
 print "your IP Address is: ",  theIP
 

def mailGonder(gonderilecekData): 
 SMTP_SERVER = 'smtp.gmail.com'
 SMTP_PORT = 587
  
 gonderenMailAdresi = 'xxxx@xxxx.com'
 password = 'XXXXXXXXX'
 aliciMailAdresi = 'xxxx@xxxx.com'
 subject = 'IP Adres: '
 body = gonderilecekData + "\nIP adres: ".join(theIP)
  
 
  
 body = "" + body + ""
  
 headers = ["From: " + gonderenMailAdresi,
            "Subject: " + subject,
            "To: " + aliciMailAdresi,
            "MIME-Version: 1.0",
            "Content-Type: text/html"]
 headers = "\r\n".join(headers)
  
 session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
  
 session.ehlo()
 session.starttls()
 session.ehlo
 print 'login oluyor...'
 session.login(gonderenMailAdresi,password)
 print 'mail gonderiliyor...' 
 session.sendmail(gonderenMailAdresi, aliciMailAdresi, headers + "\r\n\r\n" + body)
 print 'gonderildi. cikiliyor...'
 session.quit()
 print 'bitti.'


eskiIpAdresi = ""
theIP=""
while 1:
 try:
  print "ip"
  print theIP
  print "eskiIp"
  print eskiIpAdresi
  if theIP == "" :
   print "ilk açılma. Yeni mail adresi alınıyor."
   getIP()
   eskiIpAdresi=theIP
   mailGonder("İlk açılma ")
  elif eskiIpAdresi != theIP:
   getIP() 
   eskiIpAdresi = theIP
   print "ip adresi farkli mail gonderiliyor"
   mailGonder("IP değişti: ")
  else:
   getIP()
   print "IP ayni"
  print "uyuyor..."
  time.sleep(10) 
 except KeyboardInterrupt:
  raise
 except:
      print "Unexpected error:", sys.exc_info()[0]





Daha sonra  "sudo nano /etc/rc.local" ile rc.local dosyasına aşağıdaki satırı ekleyin.

"screen -d -m python /home/getIP.py"
(NOT: exit 0 satırının üstünde olmalı.)

CTRL+X tuşu ile çıkış işlemini yapın. "E" ve enter tuşuna basıp kaydederek nano uygulamasından çıkın.

Bu sayede getIP.py dosyamız her açılışta yeni bir screen açıp arka planda çalışacaktır.

Not: bu işlem için screen (sudo apt-get install screen) ve python bileşenlerinin yüklü olması gereklidir.

Bundan sonra raspberry pi her açılışta yada her IP değişiminde size mail atarak IP adresini bildirecektir.

Örnek dosyayı bu linkten indirebilirsiniz: https://www.dropbox.com/s/zrokab9weg31uk9/getIP_.py

Hiç yorum yok:

Yorum Gönder