expect远程登录服务器并执行命令

#!/usr/bin/expect
set timeout 120            #设置执行超时时间,任何输入120秒后退出
set password "password"         #set设置password名,值为password
spawn ssh -p 端口 root@ip     #连接用户主机账号
expect "*password" { send "$password "}     #定义命令开始,并发送字符, 为回车符
expect "*]#"      #定义命令开始
send "eval sed -i 's!gcomm://!gcomm://$IP_2!g' /etc/my.cnf.d/server.cnf "    #发送命令并执行
expect "*]#"
send " "
expect "*]#"
send "/etc/init.d/mysql restart "
expect "*]#"
send "logout "     
expect eof       #最后别忘记加这句,否则会得不到正确的结果

原文地址:https://www.cnblogs.com/tiantianhappy/p/9139937.html