sshpass-win32 icon indicating copy to clipboard operation
sshpass-win32 copied to clipboard

I found sshpass failed while use it with read -r in git bash

Open jokerYan-today opened this issue 2 months ago • 1 comments

测试案例

REMOTE_HOST=""
REMOTE_USER="root"
REMOTE_PASSWORD=""
SSH_PORT=""


# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 执行远程命令的抽象函数
remote_exec() {
    local remote_cmd="$1"
    local use_strict_key_checking="${2:-false}"
    
    local strict_key_option=""
    if [ "$use_strict_key_checking" = "true" ]; then
        strict_key_option="-o StrictHostKeyChecking=no"
    fi
    
    log "执行远程命令: $remote_cmd"
    log "使用参数: -p $SSH_PORT $strict_key_option $REMOTE_USER@$REMOTE_HOST"
    
    # 使用双引号包裹密码,确保变量正确替换
    sshpass -p "$REMOTE_PASSWORD" ssh -p $SSH_PORT $strict_key_option $REMOTE_USER@$REMOTE_HOST "$remote_cmd"
}

# 模拟文件列表
test_files="xx.txt
xx1.txt
xx2.txt"

log "=== 测试1: 在read循环外使用sshpass ==="
remote_exec "echo '循环外测试成功'"

log "=== 测试2: 在read循环内使用sshpass ==="
echo "$test_files" | while IFS= read -r file; do
    if [ -n "$file" ]; then
        log "处理文件: $file"
        
        # 在循环内调用sshpass
        if remote_exec "echo '处理文件: $file'"; then
            log "循环内sshpass成功: $file"
        else
            log "循环内sshpass失败: $file"
            exit 1
        fi
    fi
done

log "=== 测试3: 使用进程替换避免子shell问题 ==="
while IFS= read -r file; do
    if [ -n "$file" ]; then
        log "处理文件: $file"
        
        # 在循环内调用sshpass
        if remote_exec "echo '进程替换测试: $file'"; then
            log "进程替换sshpass成功: $file"
        else
            log "进程替换sshpass失败: $file"
            exit 1
        fi
    fi
done < <(echo "$test_files")

log "=== 测试4: 使用临时文件避免管道问题 ==="
echo "$test_files" > /tmp/test_files.txt
while IFS= read -r file; do
    if [ -n "$file" ]; then
        log "处理文件: $file"
        
        # 在循环内调用sshpass
        if remote_exec "echo '临时文件测试: $file'"; then
            log "临时文件sshpass成功: $file"
        else
            log "临时文件sshpass失败: $file"
            exit 1
        fi
    fi
done < /tmp/test_files.txt
rm -f /tmp/test_files.txt

log "所有测试完成!"

while i test it on windows10 ,i found it can't use with read in a loop

jokerYan-today avatar Oct 24 '25 02:10 jokerYan-today

i test it on linux , it's ok, maybe it has some probrems on windows version

jokerYan-today avatar Oct 24 '25 02:10 jokerYan-today