Linux系统中的expect是一个用于实现自动交互式的命令,一般情况下,在执行某些命令、脚本或者程序时,需要我们手动从终端输入交互指令后才能继续执行,而expect则可以根据交互的提示,模拟标准输入,最终实现自动化交互。
yum -y install expect
参数说明
参数 | 说明 |
send | 向进程发送字符串 |
expect | 从进程接收字符串 |
spawn | 启动新的进程 |
interact | 允许用户交互 |
expect用法实例
远程登录
#!/usr/bin/expect set hostname "10.10.200.200" set username "myname" set password "MyPassword" spawn ssh $username@$hostname expect { "yes/no" {send "yes\r"; exp_continue} "password:" {send "$password\r"} } interact
切换用户
#!/usr/bin/expect -f spawn su - Uman expect "*password*" send "UpassWord\r" interact
执行命令
#!/usr/bin/expect set hostname "10.10.200.200" set username "myroot" set password "MyPassword" spawn ssh $username@$hostname expect { "yes/no" {send "yes\r"; exp_continue} "password:" {send "$password\r"} } expect "]*" send "cd /opt\r" expect "opt]*" send "echo 1234 > 12.txt\r" expect "]*\r" send "exit\r"
原创文章禁止转载:技术学堂 » Linux安装expect及用法实例