转义预期发送的所有特殊字符 bash

Escape all special chars for expect send in bash

我需要通过 telnet 将一些带有 expect 的字符串发送到系统并获得以下示例字符串:

    $ cat SERVERTEMPPASSWORDLIST.txt
    SID=21|21|asldf8j2sRa2255||2840400|
    SID=21|27|ala"sd8fjs2A"$||2840400|alsd8fj2s%"aa
    SID=21|27|alsd"8fujs!"sl9a2e4|asdf2$sa5|2840400|asdfs2asl92
    SID=21|21|holysshit||2840400|

脚本必须这样做:

    $ cat test.sh
    #!/usr/bin/env bash
    (
        grep -E "SID=${sid}" SERVERTEMPPASSWORDLIST.txt | while read line; do
            TCID=$(echo ${line} | cut -d '|' -f 2)
            TSPW="$(echo ${line} | cut -d '|' -f 3)"
            TCPW="$(echo ${line} | cut -d '|' -f 4)"
            DURATION="$(echo ${line} | cut -d '|' -f 5)"
            DESC="$(echo ${line} | cut -d '|' -f 6)"

            if [[ "${TCPW}" != "" ]]; then
                cat <<- ADDENTRY
                    expect "error id=0 msg=ok"
                    send "addentry pw=${TSPW} desc=${DESC} duration=${DURATION} tcid=${TCID} tcpw=${TCPW}\r"
                ADDENTRY
            else
                cat <<- ADDENTRY
                    expect "error id=0 msg=ok"
                    send "addentry pw=${TSPW} desc=${DESC} duration=${DURATION} tcid=${TCID}\r"
                ADDENTRY
            fi
        done
    ) | expect > RESULT.txt

关于某些特殊字符,如 " 和 $,它会失败并显示错误消息,例如在右引号后有一些额外的字符,或者找不到变量 'sa5'。

    $ ./test.sh
    extra characters after close-quote
        while executing
    "send "addentry pw=ala"s"

我需要用 expect 发送的一些文本已经转义,因为空格需要作为 '\s' 而不是 ' ' 发送。例如,你会发送

    Hello World!

    Hello\sWorld!

重要的是,没有双重转义。

解决方法是将字符串设置成大括号:

            cat <<- ADDENTRY
                expect "error id=0 msg=ok"
                send {addentry pw=${TSPW} desc=${DESC} duration=${DURATION} tcid=${TCID} tcpw=${TCPW}}
                expect "error id=0 msg=ok"
                send "\r"
            ADDENTRY

像这样混合使用多种语言会让您感到悲伤。只需使用期望。而且,你在产卵什么?

#!/usr/bin/env expect

set sid [lindex $argv 0]
set fid [open SERVERTEMPPASSWORDLIST.txt r]

spawn ???

while {[gets $fid line] != -1} {
    if { ! [string match "*SID=$sid*" $line} continue

    # string replacements
    set line [string map {{ } {\s} {"} {\"}} $line]
    lassign [split $line |] tcid tspw tcpw duration desc

    if {$tcpw ne ""} {
        expect "error id=0 msg=ok"
        send "addentry pw=$tspw desc=$desc duration=$duration tcid=$tcid tcpw=$tcpw\r"
    } else {
        expect "error id=0 msg=ok"
        send "addentry pw=$tspw desc=$desc duration=$duration tcid=$tcid tcpw=$tcpw\r"
    }
}

并将 SID 作为第一个参数传递给 expect 脚本