【2015.08.25】Linux管理--sshpass

1060阅读 0评论2015-08-25 Joker_ora
分类:LINUX

简介
    借助sshpass+ssh或者使用expect实现交互式密码登陆或密钥推送

具体方法
方法一  sshpass+ssh

首先需要安装sshpass(系统中默认没有这个命令,安装过程不再描述)
向远程主机传送文件后将公钥导入到目标主机的authorited_keys文件内

点击(此处)折叠或打开

  1. Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
  2.    -f filename Take password to use from file
  3.    -d number Use number as file descriptor for getting password
  4.    -p password Provide password as argument (security unwise)
  5.    -e Password is passed as env-var "SSHPASS"
  6.    With no parameters - password will be taken from stdin

  7.    -h Show help (this screen)
  8.    -V Print version information
  9. At most one of -f, -d, -p or -e should be used

点击(此处)折叠或打开

  1. #!/bin/bash
  2. #this script is to send pub key to romote host
  3. #authors:
  4. #date:
  5. for remote_ip in `cat IP.txt`
  6. do
  7. echo "###################"
  8. sshpass -p "yourpasswd" scp -o StrictHostKeyChecking=no ~/.ssh/id_rsa.pub remote_user@${remote_ip}:/path 
  9. ssh remote_user@remote_ip <<-eof
  10. cat /path/id_rsa.pub >>/home/remote_user/.ssh/authorized_keys
  11. rm -f /path/id_rsa.pub
  12. eof
  13. #或者ssh remote_user@remote_ip "cat /path/id_rsa.pub >>/home/remote_user/.ssh/authorized_keys;rm -f /path/id_rsa.pub"
  14. done
解释:
只需提前将需要推送公钥的主机IP地址写到同一个文件内,这里为IP.txt,然后执行该脚本即可。
-o StrictHostKeyChecking=no

对于ssh的第一次登陆,会提示:
“Are you sure you want to continue connecting (yes/no)”,这时用sshpass会不好使,可以在执行的命令后面添加
 
-o StrictHostKeyChecking=no 来解决。
由于ssh-copy-id 不支持该选项我们的实现方式为先将id_pub.sh利用scp推送到远程主机,后执行远程命令将内容导入到认证文件authoritied_keys,取得和ssh-copy-id的效果,最后再删除传送的文件即可。
如果需要ssh到目标机器上sudo执行命令,可以使用ssh -t 

方法二  利用expect
上一篇:【2015.08.25】Linux安全--ssh
下一篇:【2015.08.26】Linux命令--grep正则表达式元字符集(基本集)