LoginSignup
3
4

More than 5 years have passed since last update.

Slack経由でRaspberryPiのIPアドレスを取得する

Posted at

Slack経由でRaspberryPiのIPアドレスを取得する

1. はじめに

どうもISAOXです。
今回もSlack経由でRaspberryPiに何かやらせるシリーズです。
以下の投稿記事でSlack上でBOTに命令を出せば遠隔のRaspberryPi(以下RPi)のスクリプトを実行できるようになりました。
この記事の環境もこれをベースにしてます。参考下さい。

今回はRPiのIPアドレスをSlackにメッセージを送信させます。
IPアドレスはちょっとした時に知りたい情報です。
これができれば、sshでネットワーク経由でRPiに接続できたりできます。

2. 前提条件

この記事の前提条件は以下です。

  • インターネットに接続したRaspberryPi(Raspbian)がある。
  • RPi上でHUBOTを起動できる環境にしている
  • Slackを利用している + Slack上でHUBOT用のBOTを追加している。

3. RPiにIPアドレスを取得させる道具の準備

RPi上でのIPアドレス取得は以下のコマンドを使います。
ifconfig

なので、ifconfigを実行するShellスクリプトを用意してRPi上に配置します。
コマンドオプションも渡せる仕様です。

ifconfig_cmd.sh
#!/bin/sh

ifconfig $@

4. RPi上のHUBOTがShellスクリプトを呼ぶ準備

RPi上のHUBOTが読み込むcoffeeスクリプトに『ifconfig』という文字列が来たら上記Shellスクリプトを呼び出す命令を追記します。
追記したらRPiを再起動するなどしてHUBOTが最新のcoffeeスクリプトを読み込んでおくようにしておきましょう。

test.coffee
  robot.respond /ifconfig (.*)|ifconfig/i, (msg) ->
    # msg.send "match[0]: #{msg.match[0]}"
    # msg.send "match[1]: #{msg.match[1]}"
    arg = msg.match[1]
    @exec = require('child_process').exec
    command = "sudo -u pi sh /home/pi/GitHub/StudyRPi/Hubot/iotbot/my_exec/ifconfig_cmd.sh"
    command = "#{command} #{arg}" if arg?
    msg.send "Command: #{command}"
    @exec command, (error, stdout, stderr) ->
    msg.send error if error?
    msg.send stdout if stdout?
    msg.send stderr if stderr?

5. Slack上のBOTにIPアドレスを取得するように命令する

Slack上でBOTに以下のようにしてIPアドレスを取得するよう命令します。
するとBOTが反応しRPiのShellスクリプトを実行してくれました!
Picture
※上のスクリーンショットはSlack上の『DIRECT MESSAGES』上で入力しているので頭に指定するBOT名は省略してます。

3
4
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
3
4