您的位置:首页 > 运维架构 > Shell

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

2020-12-27 23:20 1576 查看

1、expect-正则表达

(1)expect 实现无交互登录

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

(2)安装expect

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

(3)使用方法

A、定义脚本执行的shell

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

#!/usr/bin/expect

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

B、set timeout 30

设置超时时间,单位是秒,如果设为timeout -1意为永不超时,默认timeout 为10s

C、spawn

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

D、expect

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

E、send

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

命令字符串结尾要加上"\r",如果出现异常等待的状态可以进行核查。

F、exp_continue

继续执行接下来的交互操作

G、interact

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

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]#


个人公众号:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: