ssh key互信shell脚本

脚本说明

  • 此脚本的环境为centos , ubuntu下执行可能有问题
  • 执行之前请安装expect yum -y install expect
  • 把需要做互信的信息写入passwd.txt里面(非root,系统中需要存在该用户),一行一条记录,格式如下:IP 用户名 密码
  • passwd.txt与sshkey.sh放在同一文件夹下

脚本内容

    #sshkey.sh
    #!/bin/bash
    echo '#!/usr/bin/expect -f
    set timeout 10
    set ip [lindex $argv 0]
    set username [lindex $argv 1]
    set passwd [lindex $argv 2]
    spawn ssh $ip -l $username
    expect {
            "yes/no" { send "yes\r";exp_continue }
            "*assword:" { send "$passwd\r"; }
    }
    sleep 1
    send "ssh-keygen -t rsa -P \"\" -f ~/.ssh/id_rsa \r"
    sleep 1
    send "scp /home/$username/.ssh/id_rsa.pub $username@hostip:/tmp/id_rsa$ip.pub\r"
    expect {
            "yes/no" { send "yes\r";exp_continue }
            "*assword:" {send "$passwd\r"; }
    }
    sleep 1
    send "exit\r"
    sleep 2
    send "exit\r"
    sleep 2
    expect eof'>ssh1

    Hostip=`ifconfig eth0|grep -oP '(?<=inet addr:)\S+'`
    sed -i "s/hostip/$Hostip/" ssh1
    for i in `awk '{print $1}' passwd.txt`
            do
                    j=`awk -v I="$i" '{if(I==$1)print $2}' passwd.txt`
                    k=`awk -v K="$i" '{if(K==$1)print $3}' passwd.txt`
    #               l=`awk -v L="$i" '{if(L==$1)print $4}' passwd.txt`
    #               m=`awk -v M="$i" '{if(M==$1)print $5}' passwd.txt`
                    expect ssh1  $i $j $k
            done
    cat /tmp/id_rsa*.pub >> /tmp/authorized_keys
    chmod 600 /tmp/authorized_keys
    echo '#!/usr/bin/expect -f
    set timeout 15
    set ip2 [lindex $argv 0]
    set username2 [lindex $argv 1]
    set passwd2 [lindex $argv 2]
    sleep 1
    spawn scp /tmp/authorized_keys $username2@$ip2:/home/$username2/.ssh/
    expect {
            "yes/no" { send "yes\r";exp_continue }
            "*assword:" {send "$passwd2\r";}
    }
    expect eof' >scp2
    for a in `awk '{print $1}' passwd.txt`
            do
                    b=`awk -v A="$a" '{if(A==$1)print $2}' passwd.txt`
                    c=`awk -v B="$a" '{if(B==$1)print $3}' passwd.txt`
    #               l=`awk -v L="$i" '{if(L==$1)print $4}' passwd.txt`
    #               m=`awk -v M="$i" '{if(M==$1)print $5}' passwd.txt`
                    expect scp2  $a $b $c
            done
    sleep 1
    rm -rf /tmp/id_rsa*.pub
    sleep 1
    rm -rf /tmp/authorized_keys
    rm -rf ssh1
    sleep 1
    rm -rf scp2


    exit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值