已整理-sshpass 脚本应用案例
sshpass一个简单、轻量级命令行工具,提供非交互式密码验证
原理:
1、ssh 直接使用 TTY 访问,以确保密码是用户键盘输入的。 sshpass 在专门的 tty 中运行 ssh,以误导 ssh 相信它是从用户接收到的密码
2、使用 sshpass 是不安全的,因为所有系统上的用户可以看到密码。因此,在生产环境,建议使用 密钥登录。
安装:
# yum install epel-release
# yum install sshpass
命令语法:
sshpass [options] ssh user@host
options
-p password #直接提供密码
# sshpass -p '123456' ssh aaronkilik@10.42.0.1 'df -h'
-e #读取环境变量 SSHPASS,在bashrc 中添加 SSHPASS 环境变量,配置登录密码
export SSHPASS='PmN8uq48tBGwrMCY'
sshpass -e ssh user@host
# 配置别名使用更香
alias sshtup='sshpass -e ssh root@192.20.0.164 '"'"'sh /root/update.sh'"'"''
-f filename #从文件中读取密码
# sshpass -f password_filename ssh aaronkilik@10.42.0.1 'df -h'
但最好加上:ssh -o StrictHostKeyChecking=no
示例脚本如下:
#!/bin/bash
>result.txt
>error_ssh_ip.txt
>temp.txt
for i in `cat linux.txt`
do
ping -c 3 -i 0.2 -W 1 $i &> /dev/null
[ $? -eq 0 ] && echo $i" is ok" || continue
sshpass -p '123456' ssh -o StrictHostKeyChecking=no admin@$i 'ps -ef |egrep "rsyslog|rpc|rpc.statd|python|dns"|grep -v grep' &> temp.txt
if [ $? -ne 0 ] ; then
echo $i >> error_ssh_ip.txt
continue
fi
awk '{print res_ip," ",$0}' res_ip=$i temp.txt >>result.txt
done