shell study-17day--expect登录远程主机

1expect-正则表达

1)expect 实现无交互登陆

expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通讯,而无需人的干预。如:ssh登陆,ftp登陆等写在一个脚本上,使之自动化完成。shell

2)安装expect

[root@test ~]# yum -y install expect

3)使用方法

A、定义脚本执行的shell

[root@test ~]# find / -name expect 
/usr/bin/expect

#!/usr/bin/expect编程

定义的是 expect 可执行文件的连接路径.bash

Bset timeout 30

设置超时时间,单位是秒,若是设为timeout -1意为永不超时,默认timeout 为10s服务器

Cspawn

spawn 是进入expect 环境后才能执行的内部命令,若是没有装expect或直接在默认的SHELL下执行是找不到spawn命令的。不能直接在默认的shell环境中进行执行主要功能,它主要的功能是给ssh运行进程加个壳,用来传递交互指令。ssh

Dexpect

expect内部命令,主要用来判断输出结果是否包含某项字符串,没有则当即返回,不然就等待一段时间后返回,等待时间经过timeout进行设置。ide

Esend

执行交互动做,将交互要执行的动做进行输入给交互指令。工具

命令字符串结尾要加上"\r",若是出现异常等待的状态能够进行核查。spa

Fexp_continue

继续执行接下来的交互操做orm

Ginteract

执行完后保持交互状态,把控制权交给控制台;若是不加这一项,交互完成会自动退出。进程

H、$argv

expect脚本能够接受从bash传递过来的参数,能够使用 [lindex $argv n]得到,n 从 0 开始,分别表示第一个,第二个,第三个……参数。

4)免密码经过 SSH 登陆服务器(非秘钥方式)

[root@test shell]# vi ssh.sh 
"password" { send "$passwd\r" }
}
#!/usr/bin/expect
set ip "192.168.0.20"
set name "root"
set passwd "123456"
set timeout 25
spawn ssh $name@$ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$passwd\r" }
}
expect "#"  #判断上次输出结果里是否包含“password:”的字符串,若是有则当即返回,向下执行;不然就一直等待,直到超时时间到
send "touch /root/test.txt\r"
send "ls /root > /root/test.txt\r"
send "exit\r"
expect eof  #执行完成上述命令后,退出 Expect,把控制权交给控制台,变回手工操做
[root@test shell]# expect ssh.sh 
spawn ssh root@192.168.0.20
root@192.168.0.20's password: 
Last login: Fri Nov 27 00:18:47 2020 from 192.168.0.10
[root@test ~]# touch /root/test.txt
[root@test ~]# ls /root > /root/test.txt
[root@test ~]# exit
登出
Connection to 192.168.0.20 closed.
[root@test shell]#

 注:expect -f ssh.sh 会显示脚本执行不成功的报错信息。

5)批量ssh登陆服务器进行管理

[root@test shell]# cat ssh.exp 
#!/usr/bin/expect
set ipaddr [lindex $argv 0]
set passwd [lindex $argv 1]
set timeout 30
spawn ssh root@$ipaddr
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$passwd\r" }
}
expect "#"
send "cd /root\r"
send "rm -rf test.txt\r"
send "exit\r"
expect eof
[root@test shell]# 
Shell脚本传递ip及密码等参数信息:
[root@test shell]# cat login.sh 
#!/bin/bash
echo
for ip in `awk '{print $1}' /root/shell/ip_list.txt`
do
pass=`grep $ip /root/shell/ip_list.txt|awk '{print $2}'`
expect /root//shell/ssh.exp $ip $pass
done
[root@test shell]# 
ip_list.txt文件
[root@test shell]# cat ip_list.txt 
192.168.0.20 123456
[root@test shell]# 
执行脚本
[root@test shell]# sh login.sh 
spawn ssh root@192.168.0.20
root@192.168.0.20's password: 
Last login: Fri Nov 27 00:32:36 2020 from 192.168.0.106
[root@test ~]# cd /root
[root@test ~]# rm -rf test.txt
[root@test ~]# exit
登出
Connection to 192.168.0.20 closed.
[root@test shell]#


我的公众号:

image.png

相关文章
相关标签/搜索