前言:
ssh命令, 没有指定密码的参数. 以至于在脚本中使用ssh命令的时候, 必须手动输入密码, 才能继续执行. 这样使得脚本的自动化执行变得很差, 尤其当ssh对应的机器数很多的时候, 会令人抓狂.本文讲解了两种方式, 一种借助expect脚本, 一种借助sshpass来实现.
*) 借助expect脚本来实现
1. expect不是系统自带的工具, 需要安装
yum install expect -y
2. expect脚本的编写规则
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1. [#!/usr/bin/expect]告知系统脚本里的代码使用那一个shell来执行。 注意:这一行需要在脚本的第一行。 2. [set timeout <timeout>] 基本上认识英文的都知道这是设置超时时间的,现在你只要记住他的计时单位是:秒. timeout -1为永不超时3. [spawn <command>] spawn是进入expect环境后才可以执行的expect内部命令, 主要给后续的命令加个壳, 用来传递交互指令.4. [expect "<match_string>"] 这里的expect也是expect的一个内部命令,请不要惊讶.5. [send "<response_string>\r"] 这里就是执行交互动作,与手工输入内容的动作等效。 温馨提示: 命令字符串结尾别忘记加上“\r”,如果出现异常等待的状态可以核查一下.6. [interact] 执行完成后保持交互状态,把控制权交给控制台, 若要退出,使用expect eof代替7. $argv 参数数组expect脚本可以接受从bash传递过来的参数.可以使用[lindex $argv n]获得,n从0开始,分别表示第一个,第二个,第三个....参数 | 
简单例子:
| 1 2 3 4 5 6 | #! /usr/bin/expectspawn sudo apt-get install vimexpect "password"send "<password>\r"expect eof | 
这样就可以避免输入sudo密码了
3. 案例编写
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #! /bin/bashfunction auto_ssh() {  username_server="$1"  password="$2"  command="$3"  ssh_warpper="     spawn ssh -o StrictHostKeyChecking=no $username_server \"$command\"\n    expect {                                   \n      -nocase \"password:\" {send \"$password\r\"}            \n    }                                       \n    expect eof                                  \n  "  echo -e $ssh_warpper | /usr/bin/expect}auto_ssh root@172.16.1.121123456"ifconfig eth0" | 
评注:
  ssh -o StrictHostKeyChecking=no 对首次登录的机器不进行检查, 避免了用户手动输入yes/no
  echo -e $ssh_warpper, -e参数对后续字符串, 打开转义支持开关.
*) sshpass的使用
官网地址: http://sourceforge.net/projects/sshpass/
 安装sshpass
wget http://nchc.dl.sourceforge.net/project/sshpass/sshpass/1.05/sshpass-1.05.tar.gz
tar zxvf sshpass-1.05.tar.gz
cd sshpass-1.05
./configure
make && make install
或者
# yum install epel-release
已加载插件:fastestmirror
# yum repolist
# yum -y install sshpass
用法:
# sshpass
Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
-f filename Take password to use from file
-d number Use number as file descriptor for getting password
-p password Provide password as argument (security unwise)
-e Password is passed as env-var "SSHPASS"
With no parameters - password will be taken from stdin
-P prompt Which string should sshpass search for to detect a password prompt
-v Be verbose about what you‘re doing
-h Show help (this screen)
-V Print version information
At most one of -f, -d, -p or -e should be used
# export SSHPASS="user_password"
# sshpass -e ssh -p22022 root@192.168.5.77 "hostname"
Nasty PTR record "192.168.5.77" is set up for 192.168.5.77, ignoring
vic8
本文出自 “勤能补拙” 博客,请务必保留此出处http://echoroot.blog.51cto.com/11804540/1955580
原文:http://echoroot.blog.51cto.com/11804540/1955580