批量分发密钥
通过expect和ssh来完成无密码登录
expect 简介
expect 是用来进行自动化控制和测试的工具。主要是和交互式软件telnet ftp passwd fsck rlogin ssh tip 等进行自动化的交互。对于大规模的linux 运维很有帮助。expect sourceforge
expect 基本使用
在linux运维和开发中,我们经常需要远程登录服务器进行操作,登录的过程是一个交互的过程,可能会需要输入yes/no password等信息。为了模拟这种输入,可以使用expect脚本。
expect是由tcl语言演变而来的,所以expect脚本的运行需要tcl的支持。我们可以使用yum -y install tcl expect
来进行这两个软件的安装
expect 关键命令
send:向进程发送字符串,用于模拟用户的输入。注意一定要加\r回车
expect:从进程接收字符串
spawn:启动进程(由spawn启动的进程的输出可以被expect所捕获)
interact:用户交互
其中expect是关键的部分,expect英文有期待的意思,采用了tcl的模式-动作语法,此语法有以下几种模式:
单一分支语法:expect "hello" {send "test test"}
当输出中包含hello后,输出test test
多分支语法
expect { "Linux" {send "hello linux"; exp_continue} "baodian" {send "hello baodian"; exp_continue} "test" {send "hello word";} }
当输出Linux
时输出hello linux
,并接着循环此多分支语句
当输出baodian
时输出hello baodian
,并接着循环此多分支语句
当输出test时输出hello word ,并结束循环此多分支语句
里面的语句带exp_continue的语句顺序怎么写都行,如果不写exp_continue符合前面的直接就退出循环了
编写脚本
知道上面的这些我们就可以编写脚本了
#!/usr/bin/bash export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin ssh-keygen -b 1024 -f /root/.ssh/test_id_rsa -t rsa -P "" for i in 13 14 15 do IP=10.0.0.$i /usr/bin/expect <<EOF ----在shell脚本里面调用expect spawn ssh-copy-id -i /root/.ssh/test_id_rsa.pub root@$IP expect { "(yes/no)? " {send "yes\r";exp_continue} "password: " {send "1\r";} } expect eof EOF done