#!/bin/bash set -e # 或 set -o errexit config_file=${2:-'/etc/ssh/sshd_config'} config_file_bak="${config_file}_$(date "+%F__%H-%M-%S").bak" if [ ! -f "$config_file" ]; then echo file\("$config_file"\) does not exist exit 0 fi cp --preserve=mode,ownership,timestamps "$config_file" "$config_file_bak" echo "Backup created at $config_file_bak" find /etc/ssh -name "sshd_config*" # ssh port if [ -z "${1-}" ]; then while true; do read -er -p "Enter SSH port (default 22): " input_port input_port=${input_port:-22} if [[ "$input_port" =~ ^[0-9]+$ ]] && (( input_port >= 1 && input_port <= 65535 )); then port=$input_port break else echo "Invalid port. Please enter a number between 1 and 65535." fi done else port=$1 fi echo "SSH port will be set to: $port" : >"$config_file" while IFS= read -r var; do [[ $var =~ ^\#.* ]] && continue [[ $var =~ ^$ ]] && continue echo "$var" >>"$config_file" done <"$config_file_bak" # grep -q '^Port' "$config_file" && \ # sed -i "s/^Port .*/Port $port/" "$config_file" || \ # echo "Port $port" >> "$config_file" update_or_add_config() { local key=$1 local value=$2 if grep -qE "^[#]*\s*$key\s+" "$config_file"; then sed -i "s|^[#]*\s*$key\s\+.*|$key $value|" "$config_file" else echo "$key $value" >> "$config_file" fi } update_or_add_config Port "$port" update_or_add_config PermitRootLogin yes update_or_add_config PasswordAuthentication yes update_or_add_config UseDNS no echo "SSH setup complete at $(date '+%F %T')" echo "restarting sshd=========>" if command -v systemctlc >/dev/null 2>&1; then systemctl restart sshd || systemctl restart ssh else service sshd restart || service ssh restart fi