hsuetsugu’s diary

ITの技術的なことに関して主に書きます。Rとpythonとd3.jsとAWSとRaspberryPiあたりを不自由なく使いこなせるようになりたいです。

(35連休)2日目:Raspberry Pi(FTP接続、TwitterBot、ApacheWebサーバー構築)

まずは1日目に記載した、RaspberryPiの環境構築の続き。

PCからFTPでファイルやりとりするのに、CyberduckというFTPクライアントをいれてやってみようとしたがエラーになったので、修正点をメモ。

Vsftpdインストール、設定変更してサービス再起動

sudo apt-get install vsftpd
sudo service vsftpd stop
sudo vi /etc/vsftpd.conf
sudo service vsftpd start

設定変更内容

  • anonymous_enable=NO #匿名ユーザー(anonymous)のログイン禁止
  • local_enable=YES #ローカルユーザーを許可
  • write_enable=YES #書き込み許可
  • local_umask=022 #ファイル作成時のパーミッション755

Cyberduckで接続

SFTP(SSHによる暗号化FTP)で下記のように設定すると無事接続できました。

  • サーバ:[raspberrypiのIPアドレス]
  • ポート:22
  • ユーザ名:pi
  • パスワード:raspberry

f:id:hsuetsugu:20140811092347p:plain

ここから、本題のTweetBotの作成

購入した書籍ではいろいろ面倒そうなことが書かれていたが、Pythonの標準ライブラリだけで簡単に実現できるものがあったため、それを使わせていただきました。
Raspberry PiでTwitter Botを作る: uessay

  • アプリケーションを登録

http://dev.twitter.com/apps/new

  • コード一式ダウンロード

Raspberry PiをTwitter Botにするサンプル。 1.conf.txtに必要な情報を書く 2.sh twitter_setup.shを実行 3.表示されたURLをブラウザで開き認証 4.ブラウザで表示された数字7桁を入力 5.Twitterに"setup complete"と呟いていることを確認 6.以降はpython tweet.py "Hello"で呟ける 元ネタは http://d.hatena.ne.jp/Yoshiori/20100929/1285727199

  • conf.txtにAPI Key,API Secretを転記
  • アクセストークン取得用のシェルを起動

sh twitter_setup.sh

  • 表示されるURLをブラウザでみて、そこで表示された認証コードを入力

登録したTwitterアカウントで"setup complete"とツイートされていたら完了。

  • テストツイート

python tweet.py "XXX"とすれば、つぶやける。

ということで、すべてお膳立てしてもらったものを使わせてもらいましたが、これでRaspberryPiからTwitterにつぶやく仕組みが構築できました。

Apache python WEBサーバの構築

下記をほぼそのまま。
Apache/python Webサーバセットアップ on Raspberry pi - "Diary" インターネットさんへの恩返し

  • apache2インストール
sudo apt-get install apache2
  • 接続テスト

ブラウザでhttp://raspberrypi.local/が表示されればOK

  • pythonモジュールインストール
sudo apt-get install libapache2-mod-python
  • .pyファイルの許可設定
sudo vi /etc/apache2/sites-available/default

以下の3行を追加して

AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
<VirtualHost *:80>
	ServerAdmin webmaster@localhost

	DocumentRoot /var/www/
	<Directory /var/www>
		Options FollowSymLinks MultiViews
		AllowOverride None
		Order allow,deny
		allow from all
		AddHandler mod_python .py
		PythonHandler mod_python.publisher
		PythonDebug On
	</Directory>

	ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
	<Directory "/usr/lib/cgi-bin">
		AllowOverride None
		Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
		Order allow,deny
		Allow from all
	</Directory>

	ErrorLog ${APACHE_LOG_DIR}/error.log

	# Possible values include: debug, info, notice, warn, error, crit,
	# alert, emerg.
	LogLevel warn

	CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
  • ブラウザで確認
sudo vi /var/www/test.py
def index(req):
  return "Test successful";

http://raspberrypi.local/test.pyで、Test successfulと表示されていれば完了。