-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_proxy.sh
More file actions
533 lines (480 loc) · 20.4 KB
/
Copy pathsetup_proxy.sh
File metadata and controls
533 lines (480 loc) · 20.4 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#!/usr/bin/env bash
# =============================================================================
# setup_proxy.sh — Ubuntu 24.04.3 Global Proxy Configuration Script
# Coverage: shell, curl, wget, git, apt, pip, npm, yarn, pnpm,
# docker, snap, Claude Code, .NET, Go, Rust(cargo), Java(Maven/Gradle)
# Usage:
# Interactive mode (recommended): bash setup_proxy.sh
# Direct mode: bash setup_proxy.sh http://127.0.0.1:7890 user pass
# Clear proxy: bash setup_proxy.sh --clear
# =============================================================================
set -euo pipefail
# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
info() { echo -e "${CYAN}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
section() { echo -e "\n${BOLD}${BLUE}══ $* ══${NC}"; }
# ── Help ──────────────────────────────────────────────────────────────────────
usage() {
cat <<EOF
Usage:
$0 Interactive mode, step-by-step prompts
$0 <proxy_url> Set proxy directly (no authentication)
$0 <proxy_url> <user> <pass> Set proxy directly (with authentication)
$0 --clear Clear all configured proxy settings
$0 --help Show this help message
Examples:
$0 http://127.0.0.1:7890
$0 http://proxy.example.com:8080 admin secret123
$0 --clear
EOF
}
# ── Clear Proxy ───────────────────────────────────────────────────────────────
clear_proxy() {
section "Clearing all proxy settings"
# 1. shell profiles
local profiles=("$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile" "$HOME/.bash_profile")
for f in "${profiles[@]}"; do
[[ -f "$f" ]] || continue
if grep -q "# >>> proxy setup >>>" "$f" 2>/dev/null; then
sed -i '/# >>> proxy setup >>>/,/# <<< proxy setup <<</d' "$f"
success "Cleared proxy block from $f"
fi
done
# 2. /etc/environment
if [[ -f /etc/environment ]] && grep -q "http_proxy\|https_proxy\|no_proxy" /etc/environment 2>/dev/null; then
sudo sed -i '/http_proxy\|https_proxy\|HTTP_PROXY\|HTTPS_PROXY\|no_proxy\|NO_PROXY\|ftp_proxy\|FTP_PROXY/d' /etc/environment
success "Cleared /etc/environment"
fi
# 3. git
git config --global --unset http.proxy 2>/dev/null && success "Cleared git http.proxy" || true
git config --global --unset https.proxy 2>/dev/null && success "Cleared git https.proxy" || true
# 4. curl
[[ -f "$HOME/.curlrc" ]] && sed -i '/^proxy=/d' "$HOME/.curlrc" && success "Cleared ~/.curlrc"
# 5. wget
[[ -f "$HOME/.wgetrc" ]] && sed -i '/^https_proxy\|^http_proxy\|^use_proxy/d' "$HOME/.wgetrc" && success "Cleared ~/.wgetrc"
# 6. apt
[[ -f /etc/apt/apt.conf.d/99proxy ]] && sudo rm -f /etc/apt/apt.conf.d/99proxy && success "Cleared apt proxy"
# 7. pip
if [[ -f "$HOME/.config/pip/pip.conf" ]]; then
sed -i '/^proxy\s*=/d' "$HOME/.config/pip/pip.conf"
success "Cleared pip proxy"
fi
# 8. npm
npm config delete proxy 2>/dev/null && true
npm config delete https-proxy 2>/dev/null && true
success "Cleared npm proxy"
# 9. yarn
command -v yarn &>/dev/null && {
yarn config delete proxy 2>/dev/null || true
yarn config delete https-proxy 2>/dev/null || true
success "Cleared yarn proxy"
}
# 10. pnpm
command -v pnpm &>/dev/null && {
pnpm config delete proxy 2>/dev/null || true
pnpm config delete https-proxy 2>/dev/null || true
success "Cleared pnpm proxy"
}
# 11. docker
[[ -f /etc/systemd/system/docker.service.d/proxy.conf ]] && \
sudo rm -f /etc/systemd/system/docker.service.d/proxy.conf && \
sudo systemctl daemon-reload && \
sudo systemctl restart docker 2>/dev/null || true
success "Cleared docker proxy"
# 12. snap
command -v snap &>/dev/null && {
sudo snap set system proxy.http="" 2>/dev/null || true
sudo snap set system proxy.https="" 2>/dev/null || true
success "Cleared snap proxy"
}
# 13. Claude Code
if [[ -f "$HOME/.claude/settings.json" ]] && command -v python3 &>/dev/null; then
python3 - <<'PYEOF'
import json, pathlib, sys
p = pathlib.Path.home() / ".claude/settings.json"
try:
d = json.loads(p.read_text())
for k in ("HTTPS_PROXY","HTTP_PROXY","NO_PROXY","https_proxy","http_proxy","no_proxy"):
d.get("env",{}).pop(k, None)
p.write_text(json.dumps(d, indent=2, ensure_ascii=False))
print(" -> Proxy fields cleared from ~/.claude/settings.json")
except Exception as e:
print(f" -> Skipped ({e})")
PYEOF
fi
# 14. Maven settings.xml
warn "Maven/Gradle proxies must be cleared manually: ~/.m2/settings.xml and ~/.gradle/gradle.properties"
echo ""
success "All proxy settings cleared. Reload your shell: source ~/.bashrc"
exit 0
}
# ── Argument Parsing ──────────────────────────────────────────────────────────
[[ "${1:-}" == "--help" || "${1:-}" == "-h" ]] && { usage; exit 0; }
[[ "${1:-}" == "--clear" ]] && clear_proxy
PROXY_URL=""
PROXY_USER=""
PROXY_PASS=""
if [[ $# -ge 1 ]]; then
PROXY_URL="$1"
PROXY_USER="${2:-}"
PROXY_PASS="${3:-}"
else
# Interactive mode
echo -e "\n${BOLD}Ubuntu 24.04.3 Global Proxy Setup Wizard${NC}\n"
read -rp "Proxy address (e.g. http://127.0.0.1:7890): " PROXY_URL
[[ -z "$PROXY_URL" ]] && { warn "No address provided. Exiting."; exit 1; }
read -rp "Username (press Enter to skip if no auth): " PROXY_USER
if [[ -n "$PROXY_USER" ]]; then
read -rsp "Password: " PROXY_PASS; echo ""
fi
fi
# Parse URL components (scheme, host, port)
SCHEME=$(echo "$PROXY_URL" | grep -oP '^https?')
HOST_PORT=$(echo "$PROXY_URL" | sed 's|^https\?://||;s|/$||')
HOST=$(echo "$HOST_PORT" | cut -d: -f1)
PORT=$(echo "$HOST_PORT" | cut -d: -f2)
# Build full URL with or without credentials
if [[ -n "$PROXY_USER" ]]; then
ENCODED_PASS=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote('$PROXY_PASS', safe=''))" 2>/dev/null || echo "$PROXY_PASS")
PROXY_FULL="${SCHEME}://${PROXY_USER}:${ENCODED_PASS}@${HOST_PORT}"
else
PROXY_FULL="$PROXY_URL"
fi
NO_PROXY_DEFAULT="localhost,127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,.local"
echo ""
info "Proxy address : $PROXY_URL"
info "Auth user : ${PROXY_USER:-( none )}"
info "NO_PROXY : $NO_PROXY_DEFAULT"
# ── Helper Functions ──────────────────────────────────────────────────────────
ensure_dir() { mkdir -p "$1"; }
append_block() {
# append_block <file> <content-block>
local file="$1"; shift
# Remove existing proxy block first, then append
if grep -q "# >>> proxy setup >>>" "$file" 2>/dev/null; then
sed -i '/# >>> proxy setup >>>/,/# <<< proxy setup <<</d' "$file"
fi
cat >> "$file" <<<"$@"
}
PROFILE_BLOCK="
# >>> proxy setup >>>
export http_proxy=\"${PROXY_FULL}\"
export HTTP_PROXY=\"${PROXY_FULL}\"
export https_proxy=\"${PROXY_FULL}\"
export HTTPS_PROXY=\"${PROXY_FULL}\"
export ftp_proxy=\"${PROXY_FULL}\"
export FTP_PROXY=\"${PROXY_FULL}\"
export no_proxy=\"${NO_PROXY_DEFAULT}\"
export NO_PROXY=\"${NO_PROXY_DEFAULT}\"
# <<< proxy setup <<<"
# =============================================================================
section "1. Shell environment variables (~/.bashrc / ~/.zshrc)"
# =============================================================================
for rc in "$HOME/.bashrc" "$HOME/.zshrc"; do
if [[ -f "$rc" ]] || [[ "$rc" == "$HOME/.bashrc" ]]; then
touch "$rc"
append_block "$rc" "$PROFILE_BLOCK"
success "$rc"
fi
done
# =============================================================================
section "2. /etc/environment (system-wide, requires sudo)"
# =============================================================================
if sudo -n true 2>/dev/null; then
sudo sed -i '/http_proxy\|https_proxy\|HTTP_PROXY\|HTTPS_PROXY\|no_proxy\|NO_PROXY\|ftp_proxy\|FTP_PROXY/d' /etc/environment
{
echo "http_proxy=\"${PROXY_FULL}\""
echo "HTTP_PROXY=\"${PROXY_FULL}\""
echo "https_proxy=\"${PROXY_FULL}\""
echo "HTTPS_PROXY=\"${PROXY_FULL}\""
echo "ftp_proxy=\"${PROXY_FULL}\""
echo "FTP_PROXY=\"${PROXY_FULL}\""
echo "no_proxy=\"${NO_PROXY_DEFAULT}\""
echo "NO_PROXY=\"${NO_PROXY_DEFAULT}\""
} | sudo tee -a /etc/environment > /dev/null
success "/etc/environment"
else
warn "No sudo access, skipping /etc/environment (safe to ignore for non-root users)"
fi
# =============================================================================
section "3. curl (~/.curlrc)"
# =============================================================================
touch "$HOME/.curlrc"
sed -i '/^proxy=/d' "$HOME/.curlrc"
echo "proxy = ${PROXY_FULL}" >> "$HOME/.curlrc"
success "~/.curlrc"
# =============================================================================
section "4. wget (~/.wgetrc)"
# =============================================================================
touch "$HOME/.wgetrc"
sed -i '/^https_proxy\|^http_proxy\|^use_proxy\|^no_proxy/d' "$HOME/.wgetrc"
{
echo "use_proxy = on"
echo "http_proxy = ${PROXY_FULL}"
echo "https_proxy = ${PROXY_FULL}"
echo "no_proxy = ${NO_PROXY_DEFAULT}"
} >> "$HOME/.wgetrc"
success "~/.wgetrc"
# =============================================================================
section "5. git"
# =============================================================================
git config --global http.proxy "${PROXY_FULL}"
git config --global https.proxy "${PROXY_FULL}"
success "git global config"
# =============================================================================
section "6. apt (requires sudo)"
# =============================================================================
if sudo -n true 2>/dev/null; then
sudo tee /etc/apt/apt.conf.d/99proxy > /dev/null <<EOF
Acquire::http::Proxy "${PROXY_FULL}";
Acquire::https::Proxy "${PROXY_FULL}";
Acquire::ftp::Proxy "${PROXY_FULL}";
EOF
success "/etc/apt/apt.conf.d/99proxy"
else
warn "No sudo access, skipping apt proxy configuration"
fi
# =============================================================================
section "7. pip (~/.config/pip/pip.conf)"
# =============================================================================
ensure_dir "$HOME/.config/pip"
touch "$HOME/.config/pip/pip.conf"
if ! grep -q '^\[global\]' "$HOME/.config/pip/pip.conf"; then
echo -e "\n[global]" >> "$HOME/.config/pip/pip.conf"
fi
sed -i '/^proxy\s*=/d' "$HOME/.config/pip/pip.conf"
sed -i '/^\[global\]/a proxy = '"${PROXY_FULL}" "$HOME/.config/pip/pip.conf"
success "~/.config/pip/pip.conf"
# =============================================================================
section "8. npm"
# =============================================================================
if command -v npm &>/dev/null; then
npm config set proxy "${PROXY_FULL}"
npm config set https-proxy "${PROXY_FULL}"
success "npm (~/.npmrc)"
else
warn "npm not found, skipping"
fi
# =============================================================================
section "9. yarn"
# =============================================================================
if command -v yarn &>/dev/null; then
yarn config set proxy "${PROXY_FULL}" --silent 2>/dev/null || yarn config set proxy "${PROXY_FULL}"
yarn config set https-proxy "${PROXY_FULL}" --silent 2>/dev/null || yarn config set https-proxy "${PROXY_FULL}"
success "yarn (~/.yarnrc / ~/.yarnrc.yml)"
else
warn "yarn not found, skipping"
fi
# =============================================================================
section "10. pnpm"
# =============================================================================
if command -v pnpm &>/dev/null; then
pnpm config set proxy "${PROXY_FULL}"
pnpm config set https-proxy "${PROXY_FULL}"
success "pnpm (~/.npmrc)"
else
warn "pnpm not found, skipping"
fi
# =============================================================================
section "11. docker (systemd drop-in)"
# =============================================================================
if command -v docker &>/dev/null && sudo -n true 2>/dev/null; then
sudo mkdir -p /etc/systemd/system/docker.service.d
sudo tee /etc/systemd/system/docker.service.d/proxy.conf > /dev/null <<EOF
[Service]
Environment="HTTP_PROXY=${PROXY_FULL}"
Environment="HTTPS_PROXY=${PROXY_FULL}"
Environment="NO_PROXY=${NO_PROXY_DEFAULT}"
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker 2>/dev/null || warn "Failed to restart docker (may not be running)"
success "docker systemd proxy.conf"
# Docker daemon pull proxy (~/.docker/config.json)
ensure_dir "$HOME/.docker"
if command -v python3 &>/dev/null; then
python3 - <<PYEOF
import json, pathlib
p = pathlib.Path.home() / ".docker/config.json"
d = json.loads(p.read_text()) if p.exists() else {}
d.setdefault("proxies", {})["default"] = {
"httpProxy": "${PROXY_FULL}",
"httpsProxy": "${PROXY_FULL}",
"noProxy": "${NO_PROXY_DEFAULT}"
}
p.write_text(json.dumps(d, indent=2, ensure_ascii=False))
print(" -> ~/.docker/config.json updated")
PYEOF
fi
else
warn "docker not found or no sudo access, skipping"
fi
# =============================================================================
section "12. snap (requires sudo)"
# =============================================================================
if command -v snap &>/dev/null && sudo -n true 2>/dev/null; then
sudo snap set system proxy.http="${PROXY_FULL}"
sudo snap set system proxy.https="${PROXY_FULL}"
success "snap system proxy"
else
warn "snap not found or no sudo access, skipping"
fi
# =============================================================================
section "13. Claude Code (~/.claude/settings.json)"
# =============================================================================
if command -v python3 &>/dev/null; then
ensure_dir "$HOME/.claude"
python3 - <<PYEOF
import json, pathlib
p = pathlib.Path.home() / ".claude/settings.json"
d = json.loads(p.read_text()) if p.exists() else {}
d.setdefault("env", {}).update({
"HTTP_PROXY": "${PROXY_FULL}",
"HTTPS_PROXY": "${PROXY_FULL}",
"NO_PROXY": "${NO_PROXY_DEFAULT}",
"http_proxy": "${PROXY_FULL}",
"https_proxy": "${PROXY_FULL}",
"no_proxy": "${NO_PROXY_DEFAULT}",
})
p.write_text(json.dumps(d, indent=2, ensure_ascii=False))
print(" -> ~/.claude/settings.json updated")
PYEOF
success "Claude Code settings.json"
else
warn "python3 not found, skipping Claude Code configuration"
fi
# =============================================================================
section "14. Go (GOPATH tools; shell env vars already cover standard go commands)"
# =============================================================================
if command -v go &>/dev/null; then
go env -w GOPROXY="https://proxy.golang.org,direct"
go env -w GONOSUMCHECK="*"
# HTTP_PROXY/HTTPS_PROXY are passed via shell env vars — no extra step needed
success "go env GOPROXY"
else
warn "go not found, skipping"
fi
# =============================================================================
section "15. Rust / cargo (~/.cargo/config.toml)"
# =============================================================================
if command -v cargo &>/dev/null; then
ensure_dir "$HOME/.cargo"
cat > "$HOME/.cargo/config.toml" <<EOF
[http]
proxy = "${PROXY_FULL}"
[https]
proxy = "${PROXY_FULL}"
EOF
success "~/.cargo/config.toml"
else
warn "cargo not found, skipping"
fi
# =============================================================================
section "16. Maven (~/.m2/settings.xml)"
# =============================================================================
if command -v mvn &>/dev/null || [[ -d "$HOME/.m2" ]]; then
ensure_dir "$HOME/.m2"
if command -v python3 &>/dev/null; then
python3 - <<PYEOF
import re, pathlib
p = pathlib.Path.home() / ".m2/settings.xml"
proxy_block = """ <proxies>
<proxy>
<id>setup-proxy</id>
<active>true</active>
<protocol>http</protocol>
<host>${HOST}</host>
<port>${PORT}</port>
<username>${PROXY_USER}</username>
<password>${PROXY_PASS}</password>
<nonProxyHosts>${NO_PROXY_DEFAULT}</nonProxyHosts>
</proxy>
</proxies>"""
if p.exists():
text = p.read_text()
text = re.sub(r'\s*<proxies>.*?</proxies>', '', text, flags=re.DOTALL)
text = text.replace('</settings>', proxy_block + '\n</settings>')
p.write_text(text)
else:
p.write_text(f"""<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0">
{proxy_block}
</settings>""")
print(" -> ~/.m2/settings.xml updated")
PYEOF
success "~/.m2/settings.xml"
else
warn "python3 not found, skipping Maven configuration"
fi
else
warn "Maven not found, skipping"
fi
# =============================================================================
section "17. Gradle (~/.gradle/gradle.properties)"
# =============================================================================
if command -v gradle &>/dev/null || [[ -d "$HOME/.gradle" ]]; then
ensure_dir "$HOME/.gradle"
touch "$HOME/.gradle/gradle.properties"
sed -i '/^systemProp\.http\|^systemProp\.https/d' "$HOME/.gradle/gradle.properties"
{
echo "systemProp.http.proxyHost=${HOST}"
echo "systemProp.http.proxyPort=${PORT}"
echo "systemProp.http.nonProxyHosts=${NO_PROXY_DEFAULT}"
echo "systemProp.https.proxyHost=${HOST}"
echo "systemProp.https.proxyPort=${PORT}"
echo "systemProp.https.nonProxyHosts=${NO_PROXY_DEFAULT}"
[[ -n "$PROXY_USER" ]] && {
echo "systemProp.http.proxyUser=${PROXY_USER}"
echo "systemProp.http.proxyPassword=${PROXY_PASS}"
echo "systemProp.https.proxyUser=${PROXY_USER}"
echo "systemProp.https.proxyPassword=${PROXY_PASS}"
}
} >> "$HOME/.gradle/gradle.properties"
success "~/.gradle/gradle.properties"
else
warn "Gradle not found, skipping"
fi
# =============================================================================
section "18. .NET / NuGet (~/.nuget/NuGet/NuGet.Config)"
# =============================================================================
if command -v dotnet &>/dev/null; then
ensure_dir "$HOME/.nuget/NuGet"
# dotnet respects HTTP_PROXY env var; write config for nuget CLI as well
local nuget_cfg="$HOME/.nuget/NuGet/NuGet.Config"
if [[ ! -f "$nuget_cfg" ]]; then
echo '<?xml version="1.0" encoding="utf-8"?><configuration></configuration>' > "$nuget_cfg"
fi
# dotnet/nuget reads HTTP_PROXY from /etc/environment (already set above)
success ".NET (via HTTP_PROXY environment variable)"
else
warn ".NET not found, skipping"
fi
# =============================================================================
section "19. uv (Python package manager)"
# =============================================================================
if command -v uv &>/dev/null; then
# uv reads standard HTTP_PROXY / HTTPS_PROXY env vars (already set via shell profile)
success "uv (via HTTP_PROXY / HTTPS_PROXY environment variables)"
info "For persistent config, add to ~/.config/uv/uv.toml:"
info " [network]\n proxy = \"${PROXY_FULL}\""
else
warn "uv not found, skipping"
fi
# =============================================================================
# Summary
# =============================================================================
echo ""
echo -e "${BOLD}${GREEN}════════════════════════════════════════${NC}"
echo -e "${BOLD}${GREEN} All proxy settings configured!${NC}"
echo -e "${BOLD}${GREEN}════════════════════════════════════════${NC}"
echo ""
echo -e " Proxy address : ${CYAN}${PROXY_URL}${NC}"
echo -e " Auth user : ${CYAN}${PROXY_USER:-( none )}${NC}"
echo ""
echo -e "${YELLOW} Apply changes to the current shell:${NC}"
echo -e " ${BOLD}source ~/.bashrc${NC}"
echo ""
echo -e "${YELLOW} To clear all proxy settings:${NC}"
echo -e " ${BOLD}bash $0 --clear${NC}"
echo ""