shonen.hateblo.jp

やったこと,しらべたことを書く.

rubyからtelnetで接続する

別の記事を書こうとしたところ躓いてしまったので

環境

raspberrypi zero WH

やりたかったこと

rubyプログラムから動作中のdockerコンテナに対してコマンドを実行したい.

やったこと

コンテナ上でtelnetdをインストール,ホストからtelnetでアクセスしてコマンド実行.

ところでdocker要素が全く無いんですが…

詳細

telnetdのセットアップ,fooユーザの登録.passwordはbar

pi@raspberrypi-WH:~ $ sudo docker run -it --name hoge resin/rpi-raspbian:jessie
root@b9dde3530af4:/# apt update && apt install nano telnetd inetutils-inetd
...
略
...
root@b9dde3530af4:/#  /etc/init.d/inetutils-inetd restart
[ ok ] Restarting internet superserver: inetd.
root@b9dde3530af4:/#
root@b9dde3530af4:/# useradd foo
root@b9dde3530af4:/# passwd foo
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
root@b9dde3530af4:/#

ctrl p, ctrl qで抜ける.

pi@raspberrypi-WH:~ $ sudo docker ps
CONTAINER ID        IMAGE                       COMMAND                  CREATED             STATUS              PORTS               NAMES
b9dde3530af4        resin/rpi-raspbian:jessie   "/usr/bin/entry.sh /…"   11 minutes ago      Up 11 minutes                           hoge
pi@raspberrypi-WH:~ $ arp -a | grep docker
? (172.17.0.2) at 02:42:ac:11:00:02 [ether] on docker0
pi@raspberrypi-WH:~ $

dockerは 172.17.0.2

$ pi@raspberrypi-WH:~ $ cat test.rb
require 'net/telnet'

tel = Net::Telnet.new("Host" => "172.17.0.2")

tel.login("foo", "bar"){|msg| print msg}
tel.cmd("ls"){|msg| print msg}
tel.cmd("exit")
tel.close
pi@raspberrypi-WH:~ $ ruby test.rb
Raspbian GNU/Linux 8
b9dde3530af4 login: foo
Password:
Linux b9dde3530af4 4.14.34+ #1110 Mon Apr 16 14:51:42 BST 2018 armv6l

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
No directory, logging in with HOME=/
$ ls
bin   dev  home  media  opt   root  sbin  sys  usr
boot  etc  lib   mnt    proc  run   srv   tmp  var
pi@raspberrypi-WH:~ $

あっさり.試作品ならこれで良いと思う.