-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdate_ssh_config.sh
More file actions
executable file
·105 lines (95 loc) · 2.71 KB
/
Copy pathupdate_ssh_config.sh
File metadata and controls
executable file
·105 lines (95 loc) · 2.71 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
#!/bin/bash
current_path="$(dirname "$0")"
source "$current_path/cluster_helpers.sh"
# Default values
CLUSTER="bluehive3"
NODE=""
PARTITION="doppelbock"
PORT="22" # 默认SSH端口
# Parse command line arguments
while getopts "a:w:p:o:" opt; do
case $opt in
a) CLUSTER="$OPTARG" ;;
w) NODE="$OPTARG" ;;
p) PARTITION="$OPTARG" ;;
o) PORT="$OPTARG" ;;
?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
esac
done
# SSH config file path
SSH_CONFIG="$HOME/.ssh/config"
COMPUTE_HOST="$(cluster_compute_host "$CLUSTER")" || exit 1
if ! awk -v target="$COMPUTE_HOST" '
/^Host[[:space:]]/ {
n = split($0, parts, /[[:space:]]+/)
for (i = 2; i <= n; i++) {
if (parts[i] == target) {
found = 1
}
}
}
END { exit(found ? 0 : 1) }
' "$SSH_CONFIG"; then
echo "Error: Host $COMPUTE_HOST not found in $SSH_CONFIG" >&2
exit 1
fi
update_host_value() {
local host_alias="$1"
local key="$2"
local value="$3"
local tmp_file
tmp_file="$(mktemp "${SSH_CONFIG}.XXXXXX")"
awk -v target="$host_alias" -v key="$key" -v value="$value" '
function host_line_matches( i, n, parts) {
n = split($0, parts, /[[:space:]]+/)
for (i = 2; i <= n; i++) {
if (parts[i] == target) {
return 1
}
}
return 0
}
function add_key_if_missing() {
if (in_block && !updated) {
print "\t" key " " value
updated = 1
}
}
/^Host[[:space:]]/ {
add_key_if_missing()
in_block = host_line_matches()
updated = 0
print
next
}
in_block && $1 == key {
print "\t" key " " value
updated = 1
next
}
{ print }
END {
add_key_if_missing()
}
' "$SSH_CONFIG" > "$tmp_file" && mv "$tmp_file" "$SSH_CONFIG"
}
# If node is specified, use it directly
if [ -n "$NODE" ]; then
TARGET_NODE="$NODE"
# Otherwise use default logic based on partition
else
if [ "$PARTITION" = "doppelbock" ]; then
TARGET_NODE="bhg0061"
elif [ "$PARTITION" = "dmi" ]; then
TARGET_NODE="bhc0208"
elif [ "$PARTITION" = "preempt" ]; then
echo "Error: preempt partition requires a specific allocated node" >&2
exit 1
else
echo "Error: Unknown partition $PARTITION" >&2
exit 1
fi
fi
update_host_value "$COMPUTE_HOST" "Hostname" "$TARGET_NODE"
update_host_value "$COMPUTE_HOST" "Port" "$PORT"
echo "Updated SSH config for $COMPUTE_HOST ($CLUSTER) with node: $TARGET_NODE and port: $PORT"