0
0

出先でも家のグローバルIPを取得できるようにする

Posted at

出先でも家のグローバルIPを取得できるようにする

我が家はインターネッツの契約上、グローバルIPがちょくちょく変わる。
出先でお家のPCにリモートデスクトップやSSHしたい時に、グローバルIPが変わっていて詰むことが稀によくある。
なので、出先でも家のグローバルIPを取得できるようにする。

構成

  • GAS
  • RaspberryPI

仕組み

  • 自分のネットワークのグローバルIPを取得し、GASにPOSTするシェルを作り、
    常時起動したRaspberryPIのCronにそれを定期的に実行するように設定する。
  • GAS側では、受け取ったグローバルIPが以前のIPと変わっていたらメール通知する。

コード

こんな感じのスプレッドシートを用意
image.png

GASのコード

const spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
const sheet = spreadSheet.getSheetByName("index");

function doGet(e) {
  const name = e.parameter['name'];
  if (!name || name == "") {
    return createResponse({
      status: "400",
      message: "name is require"
    });
  }

  const requestIP = e.parameter['ip'];
  if (!requestIP || requestIP == "") {
    return createResponse({
      status: "400",
      message: "ip is require"
    });
  }

  const userdata = getUserDataByName(name);

  if (userdata == null) {
    return createResponse({
      status: "404",
      message: '"' + name + '" is not found'
    });
  } 

  if (requestIP != userdata.ip) {
    updateIPByName(name, requestIP);

    const address = userdata.email;
    const subject = "IP変更が検知されました";
    const body = "変更後のIP: " + requestIP
    GmailApp.sendEmail(address, subject, body);

    result = {
      status: "201",
      ip: requestIP
    }
  } else {
    result = {
      status: "200",
      ip: requestIP
    }
  }

  return createResponse(result);
}

function createResponse(obj) {
  const output = ContentService.createTextOutput();
  output.setMimeType(ContentService.MimeType.JSON);
  output.setContent(JSON.stringify(obj));
  return output;
}

function getUserDataByName(name) {
  const data = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
  const values = data.getValues();
  const idx = values.findIndex(ary => ary[0] == name);
  if (idx == -1) {
    return null;
  }
  return {
    name: values[idx][0],
    ip: values[idx][1],
    prevIP: values[idx][2],
    email: values[idx][3],
  };
}

function updateIPByName(name, ip) {
  const data = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
  const values = data.getValues();
  const idx = values.findIndex(ary => ary[0] == name);
  if (idx == -1) {
    return;
  }
  values[idx][2] = values[idx][1];
  values[idx][1] = ip;
  data.setValues(values);
}

RaspberryPIのシェルのコード

response=$(curl -s httpbin.org/ip)
ip=$(echo "$response" | jq -r '.origin')
curl -L "https://{GASのURL}?name=renon&ip=$ip"

実際に届くメール

image-6.png

おわり

出先の開発が快適になった。

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