forked from rauchg/wifi-password
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wifi-password.sh
executable file
·105 lines (84 loc) · 2.23 KB
/
wifi-password.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env sh
version="1.1.1"
airport="/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport"
if [ ! -f $airport ]; then
echo "ERROR: Can't find \`airport\` CLI program at \"$airport\"."
exit 1
fi
if [ -t 1 ]; then
verbose=1
else
verbose=
fi
usage() {
cat <<EOF
wifi-password - get the password of the current or specified WiFi network [version $version]
Usage: wifi-password [options] [ssid]
Options:
-q, --quiet Only output the password.
-V, --version Output version.
-h, --help This message.
Examples:
Get password for current network:
$ wifi-password
Get password for a specific network:
$ wifi-password MyWiFiNetwork
Only output the password:
$ wifi-password --quiet
$ wifi-password -q
Copy password to clipboard:
$ wifi-password -q | pbcopy
EOF
}
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do
case $1 in
-V | --version )
echo $version
exit
;;
-q | --quiet )
verbose=
;;
-h | --help )
usage
exit
;;
esac
shift
done
if [[ "$1" == "--" ]]; then shift; fi
# Merge args for SSIDs with spaces.
args="$@"
# Check for user-provided SSID.
if [ "" != "$args" ]; then
ssid="$@"
else
# Get current SSID.
ssid="`$airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'`"
if [ "$ssid" = "" ]; then
echo "ERROR: Could not retrieve current SSID. Are you connected?" >&2
exit 1
fi
fi
# Warn user about keychain dialog.
if [ $verbose ]; then
echo "Getting password for \"$ssid\"..."
echo "Keychain prompt incoming!"
sleep 1
fi
# Via: http://blog.macromates.com/2006/keychain-access-from-shell/
pwd="`security find-generic-password -D 'AirPort network password' -ga \"$ssid\" 2>&1 >/dev/null`"
if [[ $pwd =~ "could" ]]; then
echo "ERROR: Could not find SSID \"$ssid\". There may be no password set." >&2
exit 1
fi
pwd=$(echo "$pwd" | sed -e "s/^.*\"\(.*\)\".*$/\1/")
if [ "" == "$pwd" ]; then
echo "ERROR: Could not get password. Did you enter your Keychain credentials?" >&2
exit 1
fi
if [ $verbose ]; then
echo "\"$pwd\""
else
echo "$pwd"
fi