LoginSignup
1
0

More than 3 years have passed since last update.

puppeteerを使いChromeでルーターの管理画面にアクセスし、ルーターを再起動をする

Last updated at Posted at 2019-06-04

最近ネットの速度が遅いことがあり、ルーターを再起動してIPアドレスが変わるとしばらくは状況が改善するような事があるので、せっかく自宅のPCを24時間起動しっぱなしにしてるので、寝てる間にでも定期的にルーターを再起動するようにしようという話です。

前提

WiFiの方は今回は触れません。

準備

Node.jsのインストール

まずこれがないと話にならないのでインストールします。
「ubuntu node」なんかでググるとこちらの記事が出てくるので、参考にします。
npmで-gオプションを付けなかったので、nのインストールおよびnを使用したnodeのインストールは以下のようになりました。

$ npm install n  
$ sudo ./node_modules/.bin/n stable

PATHを通すために.zshrcに以下を記載します。
(bashの人とかは適宜必要なファイルに記載する)

if [ -d ${HOME}/node_modules/.bin ]; then
    export PATH=${HOME}/node_modules/.bin:${PATH}
fi

puppeteerのインストール

npmでインストールします。

npm install puppeteer

これで準備が整いました。

実装

さっそくソース全体行っちゃいます。

router-reboot-chrome.js
const fs = require('fs').promises;
const puppeteer = require('puppeteer');

const url = 'http://192.168.0.1/';

(async() => {
    const browser = await puppeteer.launch({headless:true, slowMo: 10, executablePath:'/usr/bin/google-chrome'});
    const page = await browser.newPage();
    await page.setViewport({width:1280, height:800});

    try {
        const userName = 'LOGIN_NAME';
        const password = 'LOGIN_PASS';
        await page.authenticate({username:userName, password:password});
        await page.goto(url);

        const indexFrame = page.frames().find(frame => frame.name() === 'INDEX');
        await indexFrame.waitForSelector('body > div > table > tbody > tr:nth-child(1) > td > table > tbody > tr:nth-child(23) > td > a');
        indexFrame.click('body > div > table > tbody > tr:nth-child(1) > td > table > tbody > tr:nth-child(23) > td > a');

        const pagesFrame = page.frames().find(frame => frame.name() === 'PAGES');
        await pagesFrame.waitForSelector('body > center > form > nobr > input[type="SUBMIT"]');
        pagesFrame.click('body > center > form > nobr > input[type="SUBMIT"]');

        await page.waitFor(200);

    } catch(e) {
        console.log(e);
    }
    browser.close();
})();

注意点(?)
1. puppeteer.launchのオプションでheadlessをどうするか指定しておく
2. 操作を行う箇所をtry{}catch(){}する

デフォルトでも puppeteer.launch のオプションに headless を指定しなければ headless:true となるようですが、開発中はむしろブラウザの挙動が見えている方が良いので headless:false としておきます。

try{}catch(){} に関しましては、waitFor 等、で例外が投げられる場合にcatchできないとブラウザを閉じられないので、 browser.close() をその外側に書いて終了するようにします。

これであとは以下を実行し、無事にルーターが再起動されたらcronに登録して定期的に再起動するようにしてやります。

$ node const browser = router-reboot-chrome.js

参考ページ

1
0
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
1
0