使用ssh、scp不需要密码

使用ssh、scp不需要密码
       --关于在大规模设备群的程序部署
 
author:kernas
email:guid.china@gmail.com
qq:78843062
create:2006.12.18  
 
关键字:ssh、密码、程序分发、pexpect
 
序言:    
    在工作中经常会有程序的安装部署或升级替换这样的任务,但较大规模的设备群情况下(上百台服务器)手动去做程序部署会是一件令大多数人头痛、手痛和不舒服的一件事情,特别是在程序分发的过程中,不需要考虑安全的问题情况下,所以用程序根据设备群预定的功能分发和配置程序,能有效的提高工作效率和工作质量。
    曾经考虑使用linux系统默认安装的secure shell工具,即ssh、scp等,使用expect实现分发过程中的用户和密码输入、验证等工作,但组合起来实现有些复杂,不太适合不同的环境,所以使用了如下方法来实现此功能。
   
一、逐台设备生成密钥对
   生成密匙对,使用的是rsa的密钥。命令 "ssh-keygen -t rsa"
   [user1@rh user1]$ ssh-keygen -t rsa
   Generating public/private rsa key pair.
   Enter file in which to save the key (/home/user1/.ssh/id_rsa):
   Created directory '/home/user1/.ssh'.
   Enter passphrase (empty for no passphrase):
   Enter same passphrase again:
   Your identification has been saved in /home/user1/.ssh/id_rsa.
   Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
   The key fingerprint is:
   e0:f0:3b:d3:0a:3d:da:42:01:6a:61:2f:6c:a0:c6:e7 user1@rh.test.com
   [user1@rh user1]$
    生成的过程中提示输入密钥对保存位置,直接回车,接受默认值就行了。接着会提示输入一个不同于你的password的密码,直接回车,让它空着。当然,也可以输入一个。(我比较懒,不想每次都要输入密码。) 这样,密钥对就生成完了。
    其中公共密钥保存在 ~/.ssh/id_rsa.pub
  私有密钥保存在 ~/.ssh/id_rsa
  然后改一下 .ssh 目录的权限,使用命令 "chmod 755 ~/.ssh"
   [user1@rh user1]$ chmod 755 ~/.ssh
   [user1@rh user1]$
  如果把这个密钥对中的公共密钥复制到你要访问的机器上去,并保存为如下文件就可以不用密码使用ssh相互访问了。 
  ~/.ssh/authorized_keys.
 
二、使用expect脚本自动实现密钥对生成
  创建一个tt.exp文件,并写入如下内容保存,使用chmod赋予执行权限,执行后可自动生成密钥。
  #!/usr/bin/expect
  
  set timeout 30
  set flag 1
  spawn ssh-keygen -t rsa
  while { $flag } {
   expect {
    "*/root/.ssh/id_rsa):"  {
     send "/r"
     }
    "*for no passphrase):" {
     send "/r"
     }
    "*same passphrase again:" {
     send "/r"
     sleep 1
     expect before
     set flag 0
     }
    "*Overwrite (y/n)?" {
     send "y/r"
     }
    eof {
     exit 0
     }
   }
  }
 
三、安装pexpect,使用其提供的两个函数自动为每台设备生成密钥对,并汇总到程序分发设备上。
  pexpect可以在 http://pexpect.sourceforge.net/下载到。
  解压并安装后,可以在安装文件的目录/example/目录下找到sshls.py,使用例子中提供的ssh和scp两个函数来实现步骤二文件的分发、执行以及生成密钥对文件的获取。(可能有人会问,为什么不直接使用这两个函数呢?不要再做这么多配置了。但一方面是直接使用这两个函数效率较低,另外执行的过程中存在失败的危险,就是说不是很方便的使用。)
  修改后的sshls.py文件如下,注意在执行此文件时,每次使用ssh函数或scp函数,只能用一个,就是说如果需要先scp再ssh的话,需要将ssh执行的内容注释掉,同样在执行ssh函数的时候需要将scp的内容注释掉。
  #!/usr/bin/env python
  '''This runs "ls -l" on a remote host using SSH.
      At the prompts enter hostname, user, and password.
  '''
  import pexpect
  import getpass
  import os
  from  cmd import *
  
  def ssh_command (user, host, password, command):
      """This runs a command on the remote host. This returns a
      pexpect.spawn object. This handles the case when you try
      to connect to a new host and ssh asks you if you want to
      accept the public key fingerprint and continue connecting.
      """
      ssh_newkey = 'Are you sure you want to continue connecting'
      child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
      i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
      if i == 0: # Timeout
          print 'ERROR!'
          print 'SSH could not login. Here is what SSH said:'
          print child.before, child.after
          return None
      if i == 1: # SSH does not have the public key. Just accept it.
          child.sendline ('yes')
          child.expect ('password: ')
          i = child.expect([pexpect.TIMEOUT, 'password: '])
          if i == 0: # Timeout
              print 'ERROR!'
              print 'SSH could not login. Here is what SSH said:'
              print child.before, child.after
              return None      
      child.sendline(password)
      return child
  
  def scp_command (user, host, password, srcfilename, remotepath):
      """This runs a command to cp file between localhost and remote host.
      This returns a pexpect.spawn object.
      """
      ssh_newkey = 'Are you sure you want to continue connecting'
      child = pexpect.spawn('scp -r %s %s@%s:%s'%(srcfilename, user, host, remotepath))
  #    child = pexpect.spawn('scp -r %s@%s:%s %s'%( user, host, remotepath, srcfilename))
      i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
      if i == 0: # Timeout
          print 'ERROR!'
          print 'SSH could not login. Here is what SSH said:'
          print child.before, child.after
          return None
      if i == 1: # SSH does not have the public key. Just accept it.
          child.sendline ('yes')
          child.expect ('password: ')
          i = child.expect([pexpect.TIMEOUT, 'password: '])
          if i == 0: # Timeout
              print 'ERROR!'
              print 'SSH could not login. Here is what SSH said:'
              print child.before, child.after
              return None      
      child.sendline(password)
      return child
  
  #init your parameters
  user = 'root'
  host = '192.168.0.10'
  password = 'password'
  srcfilename = '/tmp/program.exp'
  remotepath = '/tmp/'
  
  iphead = "192.168.0."
  devlist = []
  num = range(10,200)
  for i in num:
      tt = iphead + str(i)
      devlist.append(tt)
  devlist = tuple(devlist)
  
  for i in probelist:
      print "%s"%i
     
      child = scp_command (user, i, password, srcfilename, remotepath )
      child.expect(pexpect.EOF)
      print child.before
  
  #    child =  ssh_command (user, i, password, '/tmp/program.exp')
  #    child.expect(pexpect.EOF)
  #    print child.before
 
四、汇总公钥并分发到每台设备上
  使用步骤三的脚本收集每台设备上生成的id_rsa.pub,将所有的id_rsa.pub文件汇总为一个并改名为authorized_keys(注意,包括当前的程序分发设备的公钥文件)。
  将authorized_keys拷贝到所有设备的~/.ssh/目录下。
  
  OK,现在就可以不输入密码就使用ssh、scp等命令了,当然根据自己的需要写一些简单的shell脚本就可以实现你自己的程序分发安装功能了。
  

参考资料:
1、使ssh不用输入密码, http://www.chinaunix.net 作者:q1208c
2、expect学习笔记
3、pexpect说明
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值