.安装expect
#yum install -y expect
2.添加iplist文件
#cat iplist
192.168.213.1
192.168.213.2
192.168.213.3
192.168.213.4
192.168.213.5
3.expect脚本
3.1自动远程登录
#! /usr/bin/expect set host "192.168.213.5" set passwd "123456" spawn ssh root@$host expect { "yes/no" { send "yes\r"; exp_continue} "password:" { send "$passwd\r" } } interact
3.2.自动登录后执行命令再自动退出
#! /usr/bin/expect set host "192.168.213.5" set passwd "123456" spawn ssh root@$host expect { "yes/no" { send "yes\r"; exp_continue} "password:" { send "$passwd\r" } } expect "]*"
send "touch /tmp/12.txt\r"
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"
3.3传递函数
#!/usr/bin/expect set user [lindex $argv 0] set host [lindex $argv 1] set passwd "123456" set cm [lindex $argv 2] //cm,指命令 spawn ssh $user@$host expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect "]*" send "$cm\r" expect "]*" send "exit\r"
4.利用expect传递公钥 4.sh
#!/usr/bin/expect #define var set file [lindex $argv 0] set host [lindex $argv 1] set password "123456" spawn rsync -av $file root@$host:$file //$file为/root/.ssh/id_rsa.pub expect { "yes/no" {send "yes\r";exp_continue} "*password:" {send "$password\r"} } #expect eof //这条注释掉就不会报错了,否则会出现错误信息.
3.自动分发公钥到iplist中的对应服务器上
#!/bin/sh for ip in `cat iplist` do sh 4.sh $ip /root/.ssh/id_rsa.pub fi done
本文由 Mr Gu 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Oct 12, 2016 at 02:46 pm