LoginSignup
61
68

More than 5 years have passed since last update.

Macのネットワーク環境に合わせてHTTP_PROXYを切り替えるシェルスクリプト

Last updated at Posted at 2013-11-05

s.png

大学のネットワークに接続している時だけプロキシを設定したい時がある。

Macのネットワーク環境はnetworksetup -getcurrentlocationコマンドで取得することが出来るので、
.zshrc 辺りに以下のシェルスクリプトを書いておけばTerminalで新しいタブを開いた時に自動でプロキシを設定してくれるはずである。

proxy=proxy.hogehoge.ac.jp
switch_trigger=大学

if [ "`networksetup -getcurrentlocation`" = "$switch_trigger" ]; then
  export HTTP_PROXY=$proxy
  export FTP_PROXY=$proxy
  ...以下省略
fi

gitのプロキシ設定も書き換えたい

gitはhttp_proxyを見てくれないのでリモートリポジトリにpush出来なくて困ることがあった。そこでhttp_proxyと一緒にgitのプロキシ設定も書き換えるようにしたい。

gitのプロキシは以下のコマンドで設定出来る。--globalの代わりに--systemを使っても良い。

git config --global http.proxy $proxy
git config --global https.proxy $proxy
git config --global url."https://".insteadOf git://

逆にgit configから設定を削除したい場合はgit config --gobal --unset {item}を使えば良いので、先ほどのコマンドと組み合わせると最終的なコードは以下のようになる。

switch_proxy.sh
proxy=proxy.hogehoge.ac.jp:80
switch_trigger=大学

function set_proxy() {
  export http_proxy=$proxy
  export HTTP_PROXY=$proxy
  export ftp_proxy=$proxy
  export FTP_PROXY=$proxy
  export all_proxy=$proxy
  export ALL_PROXY=$proxy
  export https_proxy=$proxy
  export HTTPS_PROXY=$proxy

  git config --global http.proxy $proxy
  git config --global https.proxy $proxy
  git config --global url."https://".insteadOf git://
}

function unset_proxy() {
  unset http_proxy
  unset HTTP_PROXY
  unset ftp_proxy
  unset FTP_PROXY
  unset all_proxy
  unset ALL_PROXY
  unset https_proxy
  unset HTTPS_PROXY

  git config --global --unset http.proxy
  git config --global --unset https.proxy
  git config --global --unset url."https://".insteadOf
}

if [ "`networksetup -getcurrentlocation`" = "$switch_trigger" ]; then
  echo "Switch to proxy for university network"
  set_proxy
else
  unset_proxy
fi

このコードを .zshrc に保存して適当なターミナルで新しいセッションを開くと、switch_triggerで指定されたネットワーク環境下にいる時だけプロキシを通すことが出来る。
既に開いているセッションに対してプロキシを適用する方法がわからなかったが、
コードを ~/.switch_proxy 辺りに置いて、

~/.zshrc
alias nswitch=~/.switch_proxy

.zshrcに書いておくことで、nswitchとタイプしてプロキシを切り替えられるようになる。

61
68
1

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
61
68