猫の手も借したい

暇を極めた時に更新します

Linuxでプロキシをパッと切り替えられるスクリプトを書いた

学内LANからWANに接続しようとすると、間にプロキシが入ります。

普通にブラウジングするくらいならブラウザ側で自動検出できるのでいいのですが、Linuxユーザはいちいち設定を書き換えないと学内からaptが使えなかったりと不具合があって面倒です。

.bashrcに設定を書いてコメントアウトしたりして切り替えていましたが、それもなんかめんどうになってきたので一括でやってくれるスクリプトを作りました。
Ruby 2.4.1 p111で動作確認しています。

#! /usr/bin/env ruby
# coding: utf-8

# プロキシの設定
PROXY = 'http://proxy.example.com:port/'

# 各種pathを取得するクラス
class GetPath
    def home
        ENV['HOME']
    end
    def bashrc
        "#{home}/.bashrc"
    end
end

# プロキシを切り替えるクラス
class SwitchProxy
    def initialize(bashrc_path)
        @bashrc_path = bashrc_path
        @bashrc = File.open(bashrc_path, 'r') { |f| f.read }
        @buffer = String.new
        $script_dir = File.expand_path(File.dirname($0))
        @backup_path = "#{$script_dir}/backup"
    end
    def backup
        File.open(@backup_path, 'w') { |f| f.puts(@bashrc)}
    end
    def write # @bufferの中身を.bashrcに上書きするメソッド
        File.open(@bashrc_path, 'w') { |f| f.puts(@buffer)}
    end
    def clean
        backup
        @bashrc.each_line do |l|
            unless l =~ /(_proxy|_PROXY)/
                @buffer += l
            end
        end
        write
    end
    def off # .bashrcからプロキシの設定がある行を削除するメソッド
        clean
        settings = <<~EOS
                  export http_proxy=
                  export HTTP_PROXY=
                  export https_proxy=
                  export HTTPS_PROXY=
                  export ftp_proxy=
                  export FTP_PROXY=
                  EOS
        @buffer += settings
        write
    end
    def on # .bashrcにプロキシの設定を書き込むメソッド
        clean
        settings = <<~EOS
                  export http_proxy=#{PROXY}
                  export HTTP_PROXY=#{PROXY}
                  export https_proxy=#{PROXY}
                  export HTTPS_PROXY=#{PROXY}
                  export ftp_proxy=#{PROXY}
                  export FTP_PROXY=#{PROXY}
                  EOS
        @buffer += settings
        write
    end
    def rescue # 保持してるバックアップに戻すメソッド なんかあったとき用
        @backup = File.open(@backup_path, 'r') { |f| f.read }
        File.open(@bashrc_path, 'w') { |f| f.puts(@backup) }
    end
end


if PROXY == 'http://proxy.example.com:port/'
    puts 'you should be change proxy setting. please overwrite this scripts 5th line.'
    exit(0)
end

get_path = GetPath.new
switch = SwitchProxy.new(get_path.bashrc)

case ARGV[0]
when 'on'
    switch.on
when 'off'
    switch.off
when 'rescue'
    switch.rescue
else
    puts "arg: 'on','off' or 'rescue'"
    exit(0)
end


5行目を書き換えてスクリプトの設定をします。
実行権限を与えて適当なディレクトリに置いてください。おすすめはパスの通ってるディレクトリです。
ただし、レスキュー用にスクリプトと同じディレクトリにバックアップを1つだけ作成します。最初からいい感じにディレクトリ作っておくといいと思います。

最後にsource ~/.bashrcしたいのですが、色々試してもスクリプト内からする方法がわかりませんでした。うまく反映されなかったりする。
このスクリプトでプロ棋士を切り替えたあとにsource ~/.bashrcするなりターミナルを開き直すなりして対応してください。


オブジェクト指向の練習がてら意識して書いてみたけどべつにそこまでしなくて普通にスクリプト書いても良かった。