expect 交互 之shell执行命令操作

本文提供了一个使用expect工具进行远程SSH登录及文件传输的Shell脚本示例,通过定义不同的交互场景,如密码验证、超时处理等,展示了如何自动化处理常见的远程操作任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

shell 执行命令操作

/usr/bin/expect -c "
proc jiaohu {} {
    send_user expect_start
    expect {
        password {
            send ${RemotePasswd}\r;
            send_user expect_eof
            expect {
                \"does not exist\" {
send_user expect_failure
exit 10
                }
                password {
send_user expect_failure
exit 5
                }
                Password {
send ${RemoteRootPasswd}\r;
send_user expect_eof
expect {
    incorrect {
        send_user expect_failure
        exit 6
    }
    eof 
}
                }
                eof
            }
        }
        passphrase {
            send ${KeyPasswd}\r;
            send_user expect_eof
            expect {
                \"does not exist\" {
send_user expect_failure
exit 10
                }
                passphrase{
send_user expect_failure
exit 7
                }
                Password {
send ${RemoteRootPasswd}\r;
send_user expect_eof
expect {
    incorrect {
        send_user expect_failure
        exit 6
    }
    eof
}
                }
                eof
            }
        }
        Password {
            send ${RemoteRootPasswd}\r;
            send_user expect_eof
            expect {
                incorrect {
send_user expect_failure
exit 6
                }
                eof
            }
        }
        \"No route to host\" {
            send_user expect_failure
            exit 4
        }
        \"Invalid argument\" {
            send_user expect_failure
            exit 8
        }
        \"Connection refused\" {
            send_user expect_failure
            exit 9
        }
        \"does not exist\" {
            send_user expect_failure
            exit 10
        }
        
        \"Connection timed out\" {
            send_user expect_failure
            exit 11
        }
        timeout {
            send_user expect_failure
            exit 3
        }
        eof
    }
}
set timeout $TimeOut
switch $1 {
    Ssh_Cmd {
        spawn ssh -t -p $Port -o StrictHostKeyChecking=no $RemoteUser@$Ip /bin/su - root -c \\\"$Cmd\\\"
        jiaohu
    }
    Ssh_Script {
        spawn scp -P $Port -o StrictHostKeyChecking=no $ScriptPath $RemoteUser@$Ip:/tmp/${ScriptPath##*/};
        jiaohu
        spawn ssh -t -p $Port -o StrictHostKeyChecking=no $RemoteUser@$Ip /bin/su - root -c  \\\"/bin/sh /tmp/${ScriptPath##*/}\\\" ;
        jiaohu
    }
    Scp_File {
        spawn scp -P $Port -o StrictHostKeyChecking=no -r $ScpPath $RemoteUser@$Ip:${ScpRemotePath};
        jiaohu
    }
}
"
state=`echo $?`

 

转载于:https://www.cnblogs.com/sharesdk/p/8710066.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值