sshpass原理详解及自动化运维实践
什么是SSHpass?
SSHpass是一个用于非交互式SSH密码验证的工具,它能够通过命令行直接提供SSH密码,从而绕过交互式密码输入提示。这在自动化脚本和批处理操作中尤为有用。
工作原理
SSHpass的工作原理可以概括为以下几个关键点:
- 密码传递机制:SSHpass通过命令行参数、环境变量或文件等方式接收密码
- 伪终端模拟:它模拟一个伪终端(pseudo-terminal)来与SSH客户端交互
- 自动响应:当SSH客户端请求密码时,SSHpass会自动提供预先设置的密码
- 透明代理:对SSH客户端来说,整个过程就像用户手动输入了密码一样
自动化运维脚本
以下脚本使用 sshpass 通过读取配置文件的方式批量下发文件和执行命令,帮助大家更好的理解和掌握其用法:
#!/bin/bash# 配置参数
CONFIG_DIR=$(dirname "$0")
USERNAME="root"
PASSWORD="123123"
SSH_PORT="22"
LOG_FILE="${CONFIG_DIR}/automation_$(date +%Y%m%d).log"# 初始化日志函数
log() {echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}# 检查必要文件
check_files() {local required_files=("ip.txt" "ftp_file.conf" "execut_commad.conf")for file in "${required_files[@]}"; doif [[ ! -f "${CONFIG_DIR}/${file}" ]]; thenlog "错误: 缺少必要文件 ${file}"exit 1fidone# 初始化IP检查文件: > "${CONFIG_DIR}/ip_check.txt"
}# 文件传输函数
execute_ftp_transfer() {local ip=$1IFS=$'\n'for file in $(grep -v '^#' "${CONFIG_DIR}/ftp_file.conf" | grep -v '^$'); doif [[ ! -f "${CONFIG_DIR}/${file}" ]]; thenlog "${ip} ---- 错误: 文件 ${file} 不存在"continuefiif /opt/sshpass/bin/sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no -o ConnectTimeout=10 \-P "$SSH_PORT" "${CONFIG_DIR}/${file}" "${USERNAME}@${ip}:/opt/"; thenlog "${ip} ---- ${file} 文件传输成功"elselog "${ip} ---- ${file} 文件传输失败"fidone
}# 命令执行函数
execute_remote_command() {local ip=$1IFS=$'\n'for com in $(grep -v '^#' "${CONFIG_DIR}/execut_commad.conf" | grep -v '^$'); doif /opt/sshpass/bin/sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 \-p "$SSH_PORT" "${USERNAME}@${ip}" "$com"; thenlog "${ip} ---- 命令执行成功: ${com}"elselog "${ip} ---- 命令执行失败: ${com}"fisleep 3done
}# 主执行流程
main() {log "===== 自动化运维脚本开始执行 ====="check_fileswhile IFS= read -r line || [[ -n "$line" ]]; doline=$(echo "$line" | xargs) # 去除空白字符[[ -z "$line" || "$line" == \#* ]] && continue # 跳过空行和注释if ping -c 2 -W 1 "$line" >/dev/null 2>&1; thenlog "${line} ---- IP可达,开始处理"execute_ftp_transfer "$line"sleep 2execute_remote_command "$line"elselog "${line} ---- IP不可达"echo "${line} is blocked" >> "${CONFIG_DIR}/ip_check.txt"fidone < "${CONFIG_DIR}/ip.txt"log "===== 自动化运维脚本执行完成 ====="
}main
安全注意事项
虽然SSHpass提供了便利,但需要注意以下安全风险:
- 密码暴露:密码可能出现在命令行历史或进程列表中
- 缺乏加密:配置文件中的密码是明文存储的
- 推荐替代方案:在生产环境中,建议使用SSH密钥认证代替密码认证