ラベル RaspberryPi の投稿を表示しています。 すべての投稿を表示
ラベル RaspberryPi の投稿を表示しています。 すべての投稿を表示

2020年7月4日土曜日

Jupiter NotebookをRaspberry piで実行

インストール方法

公式ページにある通り

pip3 install jupyterlab

設定変更

  • config生成
  • jupyter notebook --generate-config
    

  • 書き換え場所

  • 下記でコメントインした上で鍵の場所を書くとSSL接続ができるようになる

    c.NotebookApp.keyfile '/etc/letsencrypt/live/your domain/privkey.pem'
    c.NotebookApp.certfile = '/etc/letsencrypt/live/your domain/fullchain.pem'
    
  • 追加設定
  • Raspberry Piにはモニターを付けないで使っている為、
    下記で起動時にブラウザを立ち上げないようにする
    また、ターミナルに関してもdisableとしている
    Port番号も書き換えている

    c.NotebookApp.open_browser = False
    c.NotebookApp.terminals_enabled = False
    c.NotebookApp.port = 9999
    

  • パスワード設定
  • 下記でプロンプトに打ち込む

    jupyter notebook password
    

  • デフォルトのフォルダを変える
  • c.NotebookApp.notebook_dir = '/home/pi/work'
    

Jupyter Notebookを起動

下記コマンドで実行してエラーが出ない場合はブラウザを開いてアクセスをする

jupyter lab --ip=0.0.0.0

パスワードを入力すると、noteが開く


起きたエラー

  1. 鍵がないと言われる
  2. - エラーメッセージ

    ValueError: certfile "/etc/letsencrypt/live/your domain/fullchain.pem" does not exist
    

    - 解決方法 フォルダの権限を変える

    sudo chmod 755 /etc/letsencrypt/archive/
    
  3. アクセス権がないと言われる
  4. - エラーメッセージ

    PermissionError: [Errno 13] Permission denied
    

    - 解決方法 オーナーを追加する

    sudo chown pi privkey.pem
    sudo chown pi fullchain.pem
    

起動時に実行する

細かいことを考えずにsystemdに登録する

$cat /etc/systemd/system/jupyter.service

[Unit]
Description=Jupyter Notebook

[Service]
Type=oneshot
WorkingDirectory=/home/pi/jupyter
ExecStart=/home/pi/.local/bin/jupyter lab --ip=0.0.0.0
User=pi
Group=pi

[Install]
WantedBy=multi-user.target

$sudo systemctl enable jupyter
$sudo systemctl status jupyter

2020年6月12日金曜日

公開鍵認証を用いてRaspberry PiにSSH接続する

目的

Raspberry Piにssh接続はできるが、パスワード認証だと万が一外につながった時に踏み台にされたり燃やされたりと心配なので鍵認証に変更する


以下は全てMacからパスワード認証でSSH接続をして行った

鍵を生成する

ssh-keygenと打ち、保存場所とパスワードを入れることで生成される

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/pi/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/pi/.ssh/id_rsa.
Your public key has been saved in /home/pi/.ssh/id_rsa.pub.
The key fingerprint is:
********
+----[SHA256]-----+

鍵を保存する

適当な箇所に鍵を保存する

今回は、.ssh以下にrpiフォルダを作成した

$ mkdir .ssh/rpi
$ mv id_rsa.pub .ssh/rpi/
$ mv id_rsa .ssh/rpi/

Macに秘密鍵(id_rsa)をコピーする

Macでもう一つターミナルを開く

scp 欲しいファイル ダウンロード先

$ scp pi@IPアドレス:~/.ssh/id_rsa ~/Desktop

SSH設定を変更する

ここで失敗するとSSH接続ができなくなるが、そうなった場合はRaspberry pi側本体側で操作して修正をする

sudo vim /etc/ssh/sshd_config

PermitRootLogin no
PubkeyAuthentication yes
RSAAuthentication yes
AuthorizedKeysFile %h/.ssh/rpi/id_rsa.pub
PasswordAuthentication no

上記を変更・追加をする

PermitRootLogin: ルートログインの禁止

PubkeyAuthentication: 公開鍵認証を許可

RSAAuthentication: RSA認証を許可

AuthorizedKeysFile: 公開鍵の保存場所指定

PasswordAuthentication: パスワードログインの禁止

余裕があればPasswordAuthenticationはyesのまま一回秘密鍵でのログインを実施した方が良い

設定に失敗していても、パスワードでのログインができるので


設定の有効化

$ sudo /etc/init.d/ssh restart
[ ok ] Restarting ssh (via systemctl): ssh.service

問題がなければOKと出る


接続元での確認

macのターミナルを開き、秘密鍵を指定してログインをする。

秘密鍵生成時のパスワードを聞かれるので入力すると接続される

$ ssh -i ~/Desktop/id_rsa -p 22 pi@RpiのIPアドレス
Enter passphrase for key '/Users/***/Desktop/id_rsa':
Linux raspberrypi 4.19.118-v7l+ #1311 SMP Mon Apr 27 14:26:42 BST 2020 armv7l

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.
Last login: Fri Jun 12 11:41:31 2020 from 192.168.1.2
pi@raspberrypi:~ $

また、パスワード認証形式で弾かれることも確かめておく

ssh pi@RPiのIPアドレス
pi@****: Permission denied (publickey).

macのSSH configファイルに設定を書いておく

デスクトップにあるRaspberry pi向けsshの秘密鍵をmacの何処かに保存する(以下では~/.ssh/rpi/)

下記のようにconfigファイルに設定を書く

$ mv ~/Desktop/id_rsa ~/.ssh/rpi
$ cat ~/.ssh/config

Host rpi
    HostName 192.168.1.29
    IdentityFile ~/.ssh/rpi/id_rsa
    User pi

$ ssh-add ~/.ssh/rpi/id_rsa
$ ssh rpi

Linux raspberrypi 4.19.118-v7l+ #1311 SMP Mon Apr 27 14:26:42 BST 2020 armv7l

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.
Last login: Fri Jun 12 12:52:06 2020 from 192.168.1.2
pi@raspberrypi:~ $ 

最後に

ポートスキャン対策でPort番号もデフォルトの22から他にした方が良いとされる。

しかし今回は、ローカルネットワークでの使用のみでルータで22番へのアクセスは禁止しているので変更はしない

2020年6月11日木曜日

Systemdを使用して起動時にpythonスクリプトを起動する

目的

起動時にPythonスクリプトを実行させる

Systemdの設定

cat /etc/systemd/system/sample.service

[Unit]
Description=Run Python Script

[Service]
ExecStart=/usr/bin/python3 /home/pi/Desktop/Python/sample.py
WorkingDirectory=/home/pi/Desktop/Python/
User=pi
Group=pi

[Install]
WantedBy=multi-user.target

WorkingDirectoryを設定しておけば、そのフォルダが実行時のカレントディレクトリとなる

サービスの自動起動登録

sudo systemctl enable sample.service

サービスの起動

sudo systemctl restart stocknews.service

もしも下記のエラーが出たら、systemctl daemon-reloadとする

Warning: The unit file, source configuration file or drop-ins of sample.service changed on disk. Run 'systemctl daemon-reload' to reload units

期待通りの働きをしないとき

ログが出るので確認をする

systemctl status sample.service

Raspberry PIでSeleniumを使ってスクレイピング

目的

Raspberry Pi上でSeleniumでのスクレイピングをする環境準備まで

準備

chromium-chromedriverのインストール

https://launchpad.net/ubuntu/trusty/+package/chromium-chromedriver

chromium-chromedriver 65.0.3325.181-0ubuntu0.14.04.1 in armhf (Updates)を選択し、ダウンロード

インストールにはapt-get installを使う

$sudo apt-get install chromium-chromedriver_65.0.3325.181-0ubuntu0.14.04.1_armhf.deb

Seleniumのインストール

素直に apt-getで

$sudo apt-get install selenium

これで完了です

おまけ

現在のDriverとchromiumのバージョンを調べる

$/usr/lib/chromium-browser/chromedriver -v
ChromeDriver 2.35 (0)
$chromium-browser --version
 --disable-quic --enable-tcp-fast-open --ppapi-flash-path=/usr/lib/chromium-browser/libpepflashplayer.so --ppapi-flash-args=enable_stagevideo_auto=0 --ppapi-flash-version=
Chromium 78.0.3904.108 Built on Raspbian , running on Raspbian 10

Headlessだとダウンロードされない

現状のChromeDriverのバージョンではセキュリティの関係でダウンロードができないようだ

Downloading with chrome headless and selenium

コードに下記に示した例を追加したらダウンロードが行える

def enable_download_in_headless_chrome(driver, download_dir):
    # add missing support for chrome "send_command"  to selenium webdriver
    driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

    params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
    command_result = driver.execute("send_command", params)


browser = webdriver.Chrome(driverpos, chrome_options=options, service_log_path='/dev/null')
enable_download_in_headless_chrome(browser, os.getcwd() + "/data")

Raspberry piからgithubへssh

目的

Raspberry pi 4の8G版を購入した

コードをRaspberry pi上で書こうとは思わないので、メインPCで書いてgithub経由でRPIに届けたい


SSHを有効にする

sudo raspi-config

5 Interfacing Options  Configure connections to peripherals

P2 SSH         Enable/Disable remote command line access to your Pi using SSH

と進んでYesを押すと有効となる

SSHのキーを作成する

ssh-keygen

Githubに登録

下記で出てきたものをgithubの設定のSSH keys New SSH keyに登録

cat id_rsa.pub

Raspberry piのSSH configに登録

生成した秘密鍵(id_rsa)をsshフォルダ(.ssh/github/)に移す

設定ファイルに記載する

pi@raspberrypi:~/Desktop $ cat ~/.ssh/config 
Host github.com
    HostName github.com
    IdentityFile ~/.ssh/github/id_rsa
    User git

確認

ssh github.comと打ち込み問題なくSSH接続することを確認


PTY allocation request failed on channel 0
Hi ****! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.

キーの追加

githubに接続する際に暗号化キーのパスワードを毎回聞かれる

ssh-addでキーを登録する

ssh-add ~/.ssh/id_rsa
ssh-add -l

エラーが出た場合

下記のエラーが出ることがあるので下記を打つことで解決される

Could not open a connection to your authentication agent

$ ssh-agent
$ eval `ssh-agent`

2018年6月20日水曜日

Let's EncryptをNginxで使用する

目的

自宅にSSL接続が行えるWebServerが必要になったので用意


構成

ドメイン(https://test.yoshio.me)が使えるようにする

WebサーバはNginx

サーバーとなるのはRaspberry pi3B


準備

必要なソフトのインストール

$cd certbotを置きたいパス
$sudo apt-get install git
$git clone https://github.com/certbot/certbot
$cd certbot

証明書取得

Certbotをスタンドアロンモードで使用しWebサーバー無しで証明書を取得

$./certbot-auto certonly --standalone -t

足りないパッケージが出るため、yを押して承認



2020/06/13追記

コンパイルを省略する為にスクリプトが別箇所からバイナリを取ってくるらしく必要なライブラリがハッシュが違うと言ってくる

THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them.
    pycparser==2.19 from https://www.piwheels.org/simple/pycparser/pycparser-2.19-py2.py3-none-any.whl#sha256=bc15573b7c6edd24407526dbbc7a0bd33d80d8af44231c37f58d73f56ff9cab6 (from -r /tmp/tmp.ULi7aj6FeV/letsencrypt-auto-requirements.txt (line 115)):
        Expected sha256 a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3
             Got        bc15573b7c6edd24407526dbbc7a0bd33d80d8af44231c37f58d73f56ff9cab6

    zope.component==4.6 from https://www.piwheels.org/simple/zope-component/zope.component-4.6-py2.py3-none-any.whl#sha256=74f55521dec189c08d98341edce929eba6bb2404662d1878f1b289af46f6f6a5 (from -r /tmp/tmp.ULi7aj6FeV/letsencrypt-auto-requirements.txt (line 137)):
        Expected sha256 ec2afc5bbe611dcace98bb39822c122d44743d635dafc7315b9aef25097db9e6
             Got        74f55521dec189c08d98341edce929eba6bb2404662d1878f1b289af46f6f6a5

修正方法は多くあり、apt-get install certbot

もしくはcertbot-autoを開き、Expected sha256を得られる値に書き換える



Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): xxx@xxx.xxxx

Emailアドレスを入れろ(お知らせとセキュリティ情報に使用)と言われるので、とりあえず入れる

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: A

-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
-------------------------------------------------------------------------------
(Y)es/(N)o: N
Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel): test.yoshio.me

一つ目がサービスの利用規約に同意しろ、二つ目が入力したメルアドにお知らせを送っていいかです

Cleaning up challenges
Problem binding to port 80: Could not bind to IPv4 or IPv6.

もしも既にport80が何かに使われていると上記のようなメッセージが出ますので素直にサーバーを止めます

Timeout during connect (likely firewall problem)

このエラーは80番ポートを開けていない時に出ます。80番と443番を開けておきましょう

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/test.yoshio.me/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/test.yoshio.me/privkey.pem
   Your cert will expire on 2018-09-18. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again. To non-interactively renew *all* of your certificates, run
   "certbot-auto renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Congratulations!と出たら成功です、

期限は3ヶ月なので2018-09-18まで有効の証明書を/etc/letsencrypt/live/test.yoshio.me/以下に手に入れました

Nginx設定(SSLでアクセス出来るかテスト)

nginx設定変更

設定を書き換えて、とりあえず証明書を使ってSSLを実現します

$vim /etc/nginx/sites-enabled/default

SSLを見るようにする

listen [::]:80 default_server;
#追加
listen 443 ssl;

証明書の参照

server_name _;
#追加
ssl_certificate /etc/letsencrypt/live/test.yoshio.me/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.yoshio.me/privkey.pem;

本変更で完了です nginxを起動させます

$sudo /etc/init.d/nginx start

注意点

引っかかったところとしては、SSLはポート443だが、80しか開けていなかったためアクセスできないエラーに陥った


Nginx設定(証明書自動更新準備)


webrootを使った更新

-wで設定するファイルはlet's encryptがアクセスして来る箇所になる模様、あとでnginxの設定値を変えてアクセスを許可する

sudo mkdir /var/www/letsencrypt
./certbot-auto certonly --webroot -w /var/www/letsencrypt -d test.yoshio.me --agree-tos --force-renewal -n

実行後のログで下記のようなことが出たら成功です


Requesting to rerun ./certbot-auto with root privileges...
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for test.yoshio.me
Using the webroot path /var/www/letsencrypt for all unmatched domains.
Waiting for verification...
Cleaning up challenges

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/test.yoshio.me/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/test.yoshio.me/privkey.pem
   Your cert will expire on 2018-09-18. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again. To non-interactively renew *all* of your certificates, run
   "certbot-auto renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

80番ポートをLet's Encrypt専用にする

/etc/nginx/sites-enabled/defaultを書き換えます

server {
    listen 80 default_server;
 listen [::]:80 default_server;
  
   location ^~ /.well-known {
  root /var/www/letsencrypt;
    }
 
    location / {
  return 301 https://$host$request_uri;
 }
}
server {
    listen 443 ssl;
 
 root /var/www/html;
 
 index index.html;
 
 server_name _;
 ssl_certificate /var/letsencrypt/live/test.yoshio.me/fullchain.pem;
 ssl_certificate_key /var/letsencrypt/live/test.yoshio.me/privkey.pem;
 
     location / {
     try_files $url $url/ =404;
 }
}

証明書リニューアルテスト

コマンドを叩いてテストして見る、以下のようなログが出たら完了

$./certbot-auto renew --force-renewal

Requesting to rerun ./certbot-auto with root privileges...
Saving debug log to /var/log/letsencrypt/letsencrypt.log

-------------------------------------------------------------------------------
Processing /etc/letsencrypt/renewal/test.yoshio.me.conf
-------------------------------------------------------------------------------
Plugins selected: Authenticator webroot, Installer None
Renewing an existing certificate
Performing the following challenges:
http-01 challenge for test.yoshio.me
Waiting for verification...
Cleaning up challenges

-------------------------------------------------------------------------------
new certificate deployed without reload, fullchain is
/etc/letsencrypt/live/test.yoshio.me/fullchain.pem
-------------------------------------------------------------------------------
Plugins selected: Authenticator webroot, Installer None

-------------------------------------------------------------------------------

Congratulations, all renewals succeeded. The following certs have been renewed:
  /etc/letsencrypt/live/test.yoshio.me/fullchain.pem (success)
-------------------------------------------------------------------------------

Cronを使っての自動実行

設定ファイルを用意

意味は毎月24日の朝6時に上でやったコマンドを実行してねということです

$sudo vim /etc/cron.d/letencrypt
00 06 24 * * /usr/local/certbot/certbot-auto renew --force-renewal

cronに読み込み

$sudo crontab letencrypt
$sudo crontab -l
00 06 24 * * /usr/local/certbot/certbot-auto renew --force-renewal && /etc/init.d/nginx reload

上記だと24日の朝6時という時間帯オンリーなので、本来はスクリプトに飛ばしてばらけた時間にアクセスするべきだと思う


以上!


追記(2020/06/13)

Go言語でひとまずSSLを試す方法

なお、sudoでgoを使う場合は、sudo「コマンドが見つかりません」PATHが初期化されているときの対処法を参照してroot権限で443ポートが使えるようにする

$ cat web.go 
package main

import (
  "fmt"
  "net/http"
  "log"
)

func handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello, World")
}

func main() {
  var crtPath = "/etc/letsencrypt/live/Your Domain/fullchain.pem";
  var keyPath = "/etc/letsencrypt/live/Your Domain/privkey.pem";
  http.HandleFunc("/", handler)
  log.Fatal(http.ListenAndServeTLS(":443", crtPath, keyPath, nil))
}

Raspberry Pi 3Bをセットアップするまで

久しぶりにRaspberry Piを購入したためセットアップしたのでメモを残す

環境構築

物理的なもの

  1. Mac OS HighSierraが入ったMac
  2. Raspberry Pi 3B
  3. Micro USBタイプのACアダプタ
  4. Micro SD
  5. USB接続のキーボード

物理的に必要なものは上記5つを用意

OS

OSをダウンロード、今回はサーバーを構築したかったのでRaspbian stretch liteという最小限の構成で行く

重たいのならば、近くのサーバーからダウンロード

RaspbianMirrors

Liteならば、Raspbian Liteから最新版をダウンロード


SD Cardへの書き込み

書き込み先を見つける

$diskutil list

容量が近そうなアドレスを見つける

今回のケースは、/dev/disk2であった

書き込むためにアンマウントをする

$sudo diskutil unmountDisk /dev/disk2

書き込む

$sudo dd bs=1m if=2018-04-18-raspbian-stretch-lite.img of=/dev/disk2

Raspberry pi初起動

起動

Micro SDをRaspberry piに装着し、電源オン

電源投入で赤LEDが点灯し、即隣の緑LEDが点滅するとMicroSDからデータを読み込んでいる

緑LEDが点灯しない場合は、おそらくFirmの書き込み先が異なっていたりする

SSH接続

$sudo raspi-config

コンフィグが開くので、5 Interfacing Options -> P2 SSHと選択してEnableにする

Macからssh pi@ipアドレスで接続確認

終了

基本的にはここから先はSSH経由で出来る事ばかりなので一度再起動をする

終了

$sudo shutdown -h now

再起動

$sudo shutdown -r now