• ssh key一键自动化生成公钥私钥,并自动分发上百服务器免密码交互


    题记:由于工作需要管理大量服务器,所以需要配公钥实现免密登录。

    ssh批量分发可以一键执行这个操作,但是使用ssh分发服务还需要对各个服务器进行.ssh/id_dsa.pub公钥上传,密码验证。所以需要配合expect实现ssh免密码登陆。

    在编写脚本之前,请先安装yum install expect -y

     1.编写服务器免交互生成公钥、私钥

    [root@web ~]$ vim ssh-keygen.exp
    #!/usr/bin/expect
    #set enter "
    "
    spawn ssh-keygen -t dsa
    expect {
            "*(/root/.ssh/id_dsa)" {send "
    
    ";exp_continue}
            "*(empty for no passphrase)" {send "
    
    ";exp_continue}
            "*again" {send "
    
    "}
    }
    expect eof

    2.编写批量分发公钥到各个服务器,并免密钥认证

    [root@web ~]$ vim fenfa_sshkey.sh 
    #!/bin/sh
    expect ssh-keygen.exp &>/dev/null
    . /etc/init.d/functions
    for ip in 132 133
    do
     #expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.59.$ip  >/dev/null 2>&1
     expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 192.168.59.$ip &>/dev/null
     if [ $? -eq 0 ];then
        action "192.168.59.$ip" /bin/true
     else
        action "192.168.59.$ip" /bin/false
     fi
    done
    [root@web ~]$ vim fenfa_sshkey.exp
    #!/usr/bin/expect
    if { $argc != 2 } {
     send_user "usage: expect fenfa_sshkey.exp file host
    "
     exit
    }
    #define var
    set file [lindex $argv 0]
    set host [lindex $argv 1]
    set password "123456"
    #spawn scp /etc/hosts root@10.0.0.142:/etc/hosts
    #spawn scp -P52113 $file os_admin@$host:$dir
    #spawn ssh-copy-id -i  $file "-p 52113 os_admin@$host"
    spawn ssh-copy-id -i  $file "-p 22 root@$host"
    expect {
            "yes/no"    {send "yes
    ";exp_continue}
            "*password" {send "$password
    "}
    }
    expect eof
  • 相关阅读:
    商城问题
    web基础重难点
    业务流程
    主流框架面试题
    数据库:索引-引擎-优化
    【jquey代码】基于选中的checkbox 删除对应的一行数据
    javascript中获取json对象的value,拼接到页面上
    【json对象和json格式的字符串】
    【idea中创建springMVC项目的2个坑】不识别@Autowired 以及 Mapper.xml的配置
    【eclipse和idea】创建spring项目时的一处不同
  • 原文地址:https://www.cnblogs.com/yihr/p/7173044.html
Copyright © 2020-2023  润新知