• 利用expect交互完成多台linux主机ssh key推送


    expect主要是用于自动化交互动作的。

    安装expect:yum -y install expect

    步骤:

    1.生成密钥对

    [root@localhost ~]# ssh-keygen 
    Generating public/private rsa key pair.
    Enter file in which to save the key (/root/.ssh/id_rsa): 
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /root/.ssh/id_rsa.
    Your public key has been saved in /root/.ssh/id_rsa.pub.
    The key fingerprint is:
    SHA256:p3XYrXIR/nNygTh7ahcmCX9W1SCXlGKb3eQV5timWw8 root@localhost
    The key's randomart image is:
    +---[RSA 2048]----+
    |            ..+*o|
    |            ooB =|
    |           ..* Bo|
    |         . ++o=.o|
    |        S *o*oEo |
    |         + =oOo.o|
    |        . ..Bo= +|
    |           +o. = |
    |          ...    |
    +----[SHA256]-----+
    

    2.创建expect脚本

    [root@localhost ~]# cat fenfa_sshkey.exp
    #!/usr/bin/expect
    #Use expect finish ssh_key send file
    if { $argc != 2 } {
    send_user "Usage: expect fenfa_sshkey.exp file host
    "             #判断条件,如果不满足2个参数就提示
    exit
    }
    
    #define  var
    set file [lindex $argv 0]                         #set定义变量file
    set host [lindex $argv 1]                         #set定义变量host
    set password "123456"                             #set定义变量password
    
    spawn ssh-copy-id -i $file "-p22 root@$host"      #spawn定义要执行的命令
    expect {                                          #定义expect开始
            "yes/no"        {send "yes
    ";exp_continue}        #提示“yes/no”,就发送yes并回车继续
            "*password"     {send "$password
    "}               #提示”***password“,就发送定义password变量并回车
    }
    expect eof
    

    3.如果是多台或者成千上百台怎么办?

    #!/bin/sh
    . /etc/init.d/functions
    for ip in `cat ip_list`
    do
            expect fenfa_sshkey.exp ~/.ssh/id_rsa.pub $ip
            if [ $0 -eq 0 ];then
                    action "$ip" /bin/true
            else
                    action "$ip" /bin/false
            fi
    done
    
  • 相关阅读:
    Python元类
    Python魔术方法
    Python反射
    Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
    游标使用的简单示例
    C# 指定物理目录下载文件,Response.End导致“正在中止线程”异常的问题
    “一键制作启动u盘失败”的主要原因是什么?
    IE11 不能正常方法网页
    Notepad++的右键菜单
    [datatable]排序时指定某列不可排序
  • 原文地址:https://www.cnblogs.com/hzxyf/p/13857997.html
Copyright © 2020-2023  润新知