6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

グローバルIPを取得してGoogleSpreadsheetsに書き出す

Last updated at Posted at 2014-12-16

概要

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
6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?