技術雑記帳兼日記帳

AWS、Python、Terraformの使い方をコッソリ

VPCとのVPN接続

SysOpsの問題ををしていて興味深いVPCとオンプレの接続があったので紹介

参考

https://docs.aws.amazon.com/ja_jp/whitepapers/latest/aws-vpc-connectivity-options/network-to-amazon-vpc-connectivity-options.html

Direct Connect単独構成は見たことあるけど、DirectConnect+VPNでDirect Connectの中にVPNを通すっていうのは初めて聞いた。 f:id:halhalhal1:20220108142228p:plain

再利用目的らしいけど、それ以外でここまでする必要あるのかな?

ちょっと初見殺しの問題だったけど、参考URLに利点がまとめられているので納得できた。

あけましておめでとうございます。

だいぶ放置していましたが今年から定期的に更新していきます。

変わらずAWSネタとPythonネタをやっていければと思っています。

潜っている間にAWSはアソシエイトのソリューションアーキテクトとデベロッパーを取得したので、今年はSysOpsアドミニストレータを取得して3冠を目指したいと思っています。

Pythonについては基本文法や実用面でAWS Lambdaへの組み込み(VPC内、外)はできたので、今度はTensor Flowに手が出せればと思っています。

近々の目標はSysOpsアドミニストレータの取得を目指していこうと思います。

今年もよろしくお願い致します。

WSLでssh

ssh自動起動しないので、いつもどおりsystemctlコマンド打ってもだめだった。
qiita.com 上記のリンクのコマンドラインで起動したらうまくいった。 ただ、自分の環境だとバッチファイルが起動できない。
色々ググったけどだめだから、スタートアップにショートカット作成でコマンド投入したらうまく行った。

Mac買いどきかなぁ

python WSL

やんごとなき事情でWindowsPython環境を作ったが、なれないのでWSLのUbuntuで実行環境を作った。
そのときに、turtleが表示されなかったのでメモ

以下をWindowsにインストール

sourceforge.net


Linux側で下記を設定

$ export DISPLAY=localhost:0.0

あとはturtleを使ったプログラムを動かして表示されればOK

WSL2だと「localhost」の箇所をWindowsIPアドレスにしないとだめみたい。
WSLは逆にIPを設定すると動かなかった。

Amazon S3 and boto3

忘れそうなのでメモついでにAWS CLIPythonでS3の使い方をまとめる。

docs.aws.amazon.com

S3の設定

aws s3 mb s3://バケット名
aws s3 sync images s3://バケット名/images/
aws s3 rm  s3://バケット名/ --include 'img*.jpg' --recursive --dryrun
でためして
aws s3 rm  s3://バケット名/ --include 'img*.jpg' --recursive
aws s3 ls s3://バケット名/images/

バケットを作るときに以下のNGが出た場合はAWS内で重複しているのでバケット名を替える必要がある

make_bucket failed: s3://imagebucket An error occurred (BucketAlreadyExists) when calling the CreateBucket operation: The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.

「/」のつけ忘れでフォルダ、ファイルが混同するので注意が必要

最後にpythonでimg-catの中身をS3に転送して結果をCSVに出力するプログラムを書いてみた。

import boto3, pathlib 

s3 = boto3.client('s3')

files = pathlib.Path('img-cat/').glob('*.jpg')
for file in files:
    s3.upload_file('img-cat/'+ file.name, 'バケット名', 'img-cat/' + file.name)

objs = s3.list_objects_v2(Bucket='バケット名')
csv = '{},{}\n'.format('file', 'size')

for o in objs.get('Contents'):
    key = o.get('Key')
    size = o.get('Size')
    if key[-4:]=='.jpg':
        csv += '{},{}\n'.format(key, int(size))

f = open('uplist.csv', 'w')
f.write(csv)

AWS CLIとboto3を使いこなして幸せになりたいな。

python スクレイピング その7

はじめに

今回はScrapyを使用してNPBの種類ごとの歴代最高記録のURLを取得してみた。

準備

Scrapyのインストール

$ pip install scrapy

Scrapyプロジェクトの作成

$ scrapy startproject npb
$ cd npb
$ tree
.
├── npb
│   ├── __init__.py
│   ├── items.py
│   ├── middlewares.py
│   ├── pipelines.py
│   ├── settings.py
│   └── spiders
│       └── __init__.py
└── scrapy.cfg

2 directories, 7 files

設定は「settings.py」にまとまっている模様。

item.pyに「url = scrapy.Field()」を追加する。

  • items.py
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class NpbItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    url = scrapy.Field()
    pass
# -*- coding: utf-8 -*-
import scrapy

class NpbSpiderSpider(scrapy.Spider):
    name = "npb_spider"
    allowed_domains = ["npb.jp"]
    start_urls = ["https://npb.jp/bis/history/"]

    def parse(self, response):
        for url in response.css('td.allTimeBatBmn a::attr("href")'):
            yield response.follow(url)
            
        for url in response.css('td.allTimePitBmn a::attr("href")'):
            yield response.follow(url)
        pass
  • 実行方法&結果
$ scrapy crawl npb_spider
2021-05-15 13:53:42 [scrapy.utils.log] INFO: Scrapy 2.5.0 started (bot: npb)
2021-05-15 13:53:42 [scrapy.utils.log] INFO: Versions: lxml 4.6.1.0, libxml2 2.9.10, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 21.2.0, Python 3.8.5 (default, Sep  4 2020, 07:30:14) - [GCC 7.3.0], pyOpenSSL 19.1.0 (OpenSSL 1.1.1h  22 Sep 2020), cryptography 3.1.1, Platform Linux-5.8.0-45-generic-x86_64-with-glibc2.10
2021-05-15 13:53:42 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.epollreactor.EPollReactor
2021-05-15 13:53:42 [scrapy.crawler] INFO: Overridden settings:
〜〜中略〜〜
2021-05-15 13:53:43 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/> (referer: None)
2021-05-15 13:53:45 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltb_g.html> (referer: https://npb.jp/bis/history/)
2021-05-15 13:53:46 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_l.html> (referer: https://npb.jp/bis/history/)
2021-05-15 13:53:48 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_w.html> (referer: https://npb.jp/bis/history/)
2021-05-15 13:53:49 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_nbb.html> (referer: https://npb.jp/bis/history/)
2021-05-15 13:53:50 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://npb.jp/bis/history/ltp_sho.html> (referer: https://npb.jp/bis/history/)
〜〜中略〜〜
  • 簡単な解説

下記でscrapyのプロジェクトを作成している。

$ scrapy startproject npb
$ cd npb

ここでclass名に合致したすべてのaタグのhrefを取得している。
打者成績と投手成績があるので2回取得する処理にしている。

class NpbSpiderSpider(scrapy.Spider):
    name = "npb_spider"
    allowed_domains = ["npb.jp"]
    start_urls = ["https://npb.jp/bis/history/"]

    def parse(self, response):
        for url in response.css('td.allTimeBatBmn a::attr("href")'):
            yield response.follow(url)
            
        for url in response.css('td.allTimePitBmn a::attr("href")'):
            yield response.follow(url)
        pass

まとめ

簡単かつ大規模なスクレイピングの機能が作れそう。
プロジェクト単位で管理できるので、なにかしらの素材集めをプロジェクトとして管理できそう。

python スクレイピング その6

はじめに

今回は巨人の藤田元司監督のWikiページを画像でコピーする処理を作成した。

準備

  • sele_headless.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
import time

url = 'https://ja.wikipedia.org/wiki/%E8%97%A4%E7%94%B0%E5%85%83%E5%8F%B8'

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
driver.get(url)

width = driver.execute_script("return document.body.scrollWidth")
height = driver.execute_script("return document.body.scrollHeight")
driver.set_window_size(width, height)

time.sleep(3)
driver.save_screenshot("screenshot.png")

time.sleep(3)
driver.quit()
  • 実行方法
$ python sele_screenshot.py
  • 簡単な解説

下記で現行のChromeバージョンから最適なドライバを選択してくれる。

driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)

ここがこの処理の肝だと感じる。
スクリプト実行を意図的に行える。

width = driver.execute_script("return document.body.scrollWidth")
height = driver.execute_script("return document.body.scrollHeight")
driver.set_window_size(width, height)

まとめ

「ChromeDriverManager().install()」はパス名記載しないので、すごくスタイリッシュで格好良い。
execute_script()の応用の幅がありそう。