shell之expect

xiaoxiao2021-02-28  39

在使用shell脚本时候,总会遇到交互性的命令,会提示输入密码,用户名之类的。这时候就需要使用expect了。

例如:

#!/usr/bin/expect -f set username [lindex $argv 0] set hostname [lindex $argv 1] set upload_name [lindex $argv 2] set dst_dir [lindex $argv 3] set password [lindex $argv 4] spawn scp -r $upload_name $username@$hostname:$dst_dir set timeout 3 expect { "yes/no" {send "yes\r";exp_continue} } expect "$username@$hostname's password:" set timeout 3 send "$password\r" set timeout 300 send "exit\r" expect eof

这里通过

set password [lindex $argv num]

从脚本外部传入参数,这里需要与传统的shell脚本做一个区别。 然后通过spawn、expect、send完成对交互式命令scp的操作。其他的ftp、tftp等等也可以仿照这个来写。

转载请注明原文地址: https://www.6miu.com/read-600106.html

最新回复(0)