
正文
Linux之expect非交互式功能
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
我在上一篇博文linux之SSH密钥认证 提过ssh之间的相互认证,但是每次使用ssh登录到其它服务器还是要输入密码的。
expect是用于提供自动交互的工具,自动连接被管理的服务器,不需要手动输入密码。
1、安装expect
[root@mg ~]# yum install -y expect
2、编写expect脚本,直接分发SSH公钥,不用手工输入密码。
vim /server/scripts/expect.exp
#!/usr/bin/expect #-------------CopyRight-------------
# Name:ssh send password
# Version Number:1.00
# Type:sh
# Language:expect
# Date:--
# Author:sandy
# QQ:
# Email:eeexu123@.com
# Blog:https://www.cnblogs.com/eeexu123/ if { $argc != } {
send_user "usage: expect fenfa_expect file host\n" //判断传入参数是否是2个
exit
} #define var
set file [lindex $argv ] //第一个参数是ssh公钥
set host [lindex $argv ] //第二个参数是连接的远程主机地址
set passwd "herine" //设置连接用户的密码 #send ssh key
spawn ssh-copy-id -i $file "-p 22 root@$host" //发送ssh公钥命令
expect {
"yes/no" {send "yes\r";exp_continue} //是否继续连接,expect交互式功能,自动添加yes,并继续。yes后成必须加\r回车符 } sleep 3 //等待连接到远程主机
expect "*password" //输入密码,expect交互功能,自动添加密码变量。后面加\r回车符
send "$passwd\r"
expect eof exit -onexit {
send_user "Goodbye!\n" //退出
}
3、测试
/usr/bin/expect test_expect.exp ~/.ssh/id_dsa.pub 172.16.1.72
上面一条命令可以放在脚本里,大批量建立ssh密钥连接
[root@mg scripts]# /usr/bin/expect test_expect.exp ~/.ssh/id_dsa.pub 172.16.1.72
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub -p root@172.16.1.72
The authenticity of host '172.16.1.72 (172.16.1.72)' can't be established.
RSA key fingerprint is a5::d4:::::aa::8d:f0:ce::5a:d3:f4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.1.72' (RSA) to the list of known hosts.
root@172.16.1.72's password:
Now try logging into the machine, with "ssh '-p 22 root@172.16.1.72'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting. Goodbye!
ssh远程使用命令
[root@mg scripts]# ssh root@172.16.1.72 "/sbin/ifconfig eth1"
eth1 Link encap:Ethernet HWaddr :0C::8D::
inet addr:172.16.1.72 Bcast:172.16.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe8d:/ Scope:Link
UP BROADCAST RUNNING MULTICAST MTU: Metric:
RX packets: errors: dropped: overruns: frame:
TX packets: errors: dropped: overruns: carrier:
collisions: txqueuelen:
RX bytes: (70.5 KiB) TX bytes: (38.8 KiB)
由上可以,expect交互功能在SSH免密码操作成功。








