Chinaunix首页 | 论坛 | 博客
  • 博客访问: 280156
  • 博文数量: 66
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 455
  • 用 户 组: 普通用户
  • 注册时间: 2015-11-25 09:52
个人简介

no pains no gains

文章分类

全部博文(66)

文章存档

2017年(10)

2016年(39)

2015年(17)

我的朋友

分类: 系统运维

2016-12-27 15:43:54

Linux下用expect实现ssh自动登录并执行脚本

 

expect不是系统自带的,需要安装:

        yum install expect

装完后才可执行以下脚本。

 

 ssh密码认证的登陆脚本:

Shell代码  收藏代码
  1. #!/bin/bash  
  2.   
  3. # 匹配提示符  
  4. CMD_PROMPT="\](\$|#)"  
  5.   
  6. # 要执行的脚本  
  7. script="/root/test.sh"  
  8.   
  9. username="root"  
  10. password="123456"  
  11. host="192.168.1.109"  
  12. port=22  
  13.   
  14. expect -c "  
  15.     send_user connecting\ to\ $host...\r    # 空格要转义  
  16.     spawn ssh -p $port $username@$host  
  17.     expect {  
  18.             *yes/no* { send -- yes\r;exp_continue;}  
  19.         *assword* { send -- $password\r;}  
  20.     }  
  21.     expect -re $CMD_PROMPT  
  22.     send -- $script\r  
  23.     expect -re $CMD_PROMPT  
  24.     exit  
  25. "  
  26. echo "\r"  

 

ssh公钥认证的登陆脚本:

 

Shell代码  收藏代码
  1. #!/bin/bash  
  2.   
  3. # 匹配提示符  
  4. CMD_PROMPT="\](\$|#)"  
  5.   
  6. # 要执行的脚本  
  7. script="/root/test.sh"  
  8.   
  9. username="root"  
  10. password="123456"  
  11. host="192.168.1.109"  
  12. port=22  
  13.   
  14. expect -c "  
  15.     send_user connecting\ to\ $host...\r  
  16.     spawn ssh -p $port $username@$host  
  17.     expect -re $CMD_PROMPT  
  18.     send -- $script\r  
  19.     expect -re $CMD_PROMPT  
  20.     exit  
  21. "  
  22. echo "\r"  
 

 

 1. send_user 是回显,相当于echo。

 2. spawn 是开启新的进程

 3. expect{  } 这是匹配上一条指令的输出,,比如上面spawn 那句执行完后,会提示你输入密码,提示语中会包含 password,因此就匹配*assword*,然后就send -- $password 把密码发过去。

 4. send 就是发指令到对端

 5. expect 内部有个exp_continue ,意思是重新匹配所在的expect,相当于while的continue

 6. expect 的 -re 表示匹配正则表达式

 

ps:expect 内部的指令的参数中特殊字符需在前面加\转义

 

类似的还可实现ftp登陆,自动上传下载文件等等。

阅读(2884) | 评论(0) | 转发(0) |
0

上一篇:截取字符串

下一篇:yum源

给主人留下些什么吧!~~