想搞一个使用ssh登陆批量ip地址执行命令,自动输入密码的脚本,可是ssh不能使用标准输入来实现自动输入密码,因而了解到了expect这个能够交互的命令vim
Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be. An interpreted language provides branching and high-level control structures to direct the dialogue. In addition, the user can take control and interact directly when desired, afterward returning control to the script.
spawn:开启一个进程,后面跟命令或者程序(须要作交互的,好比ssh) expect:匹配进程中的字符串 exp_continue:屡次匹配时用到 send:当匹配到字符串时发送指定的字符串信息 set:定义变量 puts:输出变量 set timeout:设置超时时间 interact:容许交互 expect eof:
#!/usr/bin/expect #使用expect解释器 spawn ssh root@192.168.56.101 #开启一个进程ssh expect { "yes/no" { send "yes\r"; exp_continue } #当匹配到"yes/no时,就是须要你输入yes or no时,发送yes字符串,\r带表回车;exp_continue继续匹配 "password:" { send "sanshen6677\r" } #当匹配到password,就是该输入密码,发送密码,并\r回车。注意{以前要有空格。 } interact #容许交互,这样你就会留在登陆以后的窗口,进行操做,没有interact程序执行完成后就跳回当前用户ip。
chmod +x sshlogin #添加权限直接执行 ./sshlogin 或者 expect sshlogin #使用expect解释器执行
#!/usr/bin/expect set user [lindex $argv 0] #定义变量,接收从0开始,bash是从1开始 set ip [lindex $argv 1] set password [lindex $argv 2] spawn ssh $user@$ip expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } interact
./sshlogin root 192.168.56.101 password123
#!/usr/bin/expect set user [lindex $argv 0] set ip [lindex $argv 1] set password [lindex $argv 2] spawn ssh $user@$ip "df -Th" #执行一条命令 expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } expect eof
#!/usr/bin/bash 使用#bash解释器 user=$1 ip=$2 password=$3 expect << EOF spawn ssh $user@$ip "df -Th" expect { "yes/no" {send "yes\r"; exp_continue} "password" {send "$password\r"} } expect eof EOF
bash sshlogin root 192.168.56.101 sanshen6677 #使用bash执行