qiita.com
qiita.com
ラズパイに固定IP振って使ったほうがこんなことしなくても良いですが、特殊なネットワーク環境であるため、仕方なくこのような手段をとったというお話
プログラム
#!/Usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
import socket
import fcntl
def ifconfig(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
result = fcntl.ioctl(s.fileno(), 0x8915 ,(ifname+'\0'*32)[:32])
except IOError:
return None
return socket.inet_ntoa(result[20:24])
class sendGmail:
username, password = '[email protected]', '********'
def __init__(self, to, sub, body):
host, port = 'smtp.gmail.com', 465
msg = MIMEText(body)
msg['Subject'] = sub
msg['From'] = self.username
msg['To'] = to
smtp = smtplib.SMTP_SSL(host, port)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.mail(self.username)
smtp.rcpt(to)
smtp.data(msg.as_string())
smtp.quit()
if __name__ == '__main__':
to = '[email protected]'
sub = 'development of Rspi IPaddress'
#有線LANアドレス
eth0_address = ifconfig('eth0')
print('eth0:%s' %(eth0))
#無線LANアドレス
wlan0_address = ifconfig('wlan0')
print('wlan0:%s' %(wlan0))
body = ' eth0:%s\n wlan0:%s' % (eth0_address, wlan0_address)
sendGmail(to, sub, body)
このプログラムに実行権限をあげて、rc.localに埋め込めばラズパイを起動したときにメールをメールを送信してくれます
実行権限を与える方法
※上記のプログラムをip_send.pyとする
pi@raspberry:$ sudo chmod 755 ip_send.py
rc.localへの記述
sudo nano /etc/rc.local
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#add
sudo python ip_send.py
exit 0