Last active
November 23, 2015 03:38
-
-
Save kota65535/aa20e8a7b115e1398acc to your computer and use it in GitHub Desktop.
スクリプトで無線LANにWi-Fi接続する -Linux編 (Raspberry Pi対応)- ref: http://qiita.com/kota65535/items/9210727d807a31054842
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -u | |
export LANG="C" | |
function usage() { | |
cat <<EOT | |
Usage: bash ${0##*/} <interface-name> <network-SSID> <password> | |
EOT | |
} | |
# 引数チェック | |
if [ $# -ne 3 ]; then usage && exit 1; fi | |
# 指定されたインターフェースが存在するか調べる | |
iwconfig $1 > /dev/null 2>&1 | |
if [ $? -ne 0 ]; then | |
echo "Device named '$1' not found." | |
exit 2 | |
fi | |
# すでに接続されていれば終了 | |
iwconfig $1 | grep -wq "ESSID:\"$2\"" && ifconfig $1 | grep -q 'inet addr' | |
if [ $? -eq 0 ]; then | |
echo "Already connected." | |
exit 0 | |
fi | |
# インターフェースを再起動 | |
ifconfig $1 down | |
ifconfig $1 up | |
if [ $? -ne 0 ]; then | |
echo "Failed to activate interface $1" | |
exit 4 | |
fi | |
# 指定のSSIDを持つアクセスポイントがあるか調べる | |
iwlist $1 scan | grep -wq "ESSID:\"$2\"" | |
if [ $? -ne 0 ]; then | |
echo "The wi-fi network with SSID:'$2' not found." | |
exit 3 | |
fi | |
# wpa_supplicantが動いていたら殺す | |
pkill -f "wpa_supplicant.+-i *$1 .*" | |
# SSIDを設定 | |
iwconfig $1 essid $2 | |
# WPA認証タイムアウト秒数 | |
WPA_AUTH_TIMEOUT=20 | |
is_connected=false | |
current_time=$(date +%s) | |
# wpa_supplicantをnohupで起動し接続。stdbufはバッファリングを防止するために必要 | |
while read -t ${WPA_AUTH_TIMEOUT} line; do | |
echo " $line" | |
echo $line | grep -wq 'CTRL-EVENT-CONNECTED' | |
if [ $? -eq 0 ]; then | |
is_connected=true | |
break | |
fi | |
# タイムアウト判定 | |
if [ $(($(date +%s) - ${current_time})) -gt ${WPA_AUTH_TIMEOUT} ]; then | |
echo "Timeout." | |
break | |
fi | |
done < <(nohup bash -c "wpa_passphrase $2 $3 | stdbuf -oL wpa_supplicant -i $1 -D wext -c /dev/stdin 2>&1 &") | |
if ! $is_connected; then | |
echo 'WPA authentication failed.' | |
pkill -f "wpa_supplicant.+-i *$1 .*" | |
exit 5 | |
fi | |
# IPアドレス割り当て | |
ifconfig $1 | grep -q 'inet addr' | |
if [ $? -ne 0 ]; then | |
dhclient $1 | |
ifconfig $1 | grep -q 'inet addr' | |
if [ $? -ne 0 ]; then | |
echo 'IP address cannot not be assgined.' | |
exit 6 | |
fi | |
fi | |
echo 'Connected successfully.' | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment