概要
Raspberry piにssh接続する際のグローバルIPを、定期的にGoogleSpreadsheetに書き込むpythonスクリプトを作ってみた。
事前準備
config.iniの作成
下記の情報をconfig.iniへまとめておく。
- Googleアカウント
- Googleアプリパスワード(アプリ固有)
- IP書き出し用に用意したGoogleスプレッドシートのスプレッドシートID
config.ini
[google]
username = ****
password = ****
spreadsheet_key = *****(スプレッドシートID)
なお、スプレッドシートIDは、*****部分に相当
https://docs.google.com/spreadsheets/d/*******/edit#gid=0
必要なライブラリのインストール
gdata使います。
sudo apt-get install python-gdata
Googleスプレッドシートを扱う独自クラス作成
IPと位置(行、列)を与えれば、アップデートできるクラス作ってみた。
- 書き出すIP
- 行
- 列
なお、シートはデフォルトで1番目のシート(od6)を選択
参考:http://qiita.com/debiru/items/27a48dfb3b1c010cd478
mySpreadsheet.py
import gdata.spreadsheets.client
import gdata.spreadsheet.service
import ConfigParser
class mySpreadsheet:
user = ''
passwd = ''
key = ''
sheet_id= ''
def __init__(self,config):
inifile = ConfigParser.SafeConfigParser()
inifile.read(config)
self.user = unicode(inifile.get("google","username"))
self.passwd = unicode(inifile.get("google","password"))
self.key = unicode(inifile.get("google","spreadsheet_key"))
self.sheet_id = 'od6'
def updateCell(self,value,row,col):
client = gdata.spreadsheet.service.SpreadsheetsService(self.user,self.passwd)
client.ProgrammaticLogin()
cell = client.UpdateCell(inputValue = value,
row = row, col = col,
key = self.key,
wksht_id = self.sheet_id)
if __name__ == "__main__":
m = mySpreadsheet('config.ini')
m.updateCell('hoge',1,1)
IPの取得からgoogleスプレッドシートへのアップデートまで
上記クラスを読み込み、IP渡せばOK
updateip.py
import json
from urllib2 import urlopen
from mySpreadsheet import *
m = mySpreadsheet('config.ini')
ip = json.load(urlopen('http://httpbin.org/ip'))['origin']
m.updateCell(ip,1,2)
print ip