linux服务器配置免密小脚本

首先创建服务器配置文件,文件名:sship.txt
写入要配置免密的机器ip,

172.44.0.xx
172.44.0.xx
172.44.0.xx

注:一行一ip,密码必须统一一致

创建脚本文件,文件名:sshsetup.exp
写入内容:

#!/bin/bash
##!/usr/bin/expect

## use by root
## 给一个用户创建互信 
## expect sshsetup.exp $user $password $home $ip_list_file 
## expect sshsetup.exp gprds gp123 /data7/gprds ip.txt 
##                     0     1     2            3
set user [lindex $argv 0]
set password [lindex $argv 1]
set home [lindex $argv 2]
set host [lindex $argv 3]
set currdir [exec pwd]

exec rm -rf $currdir/ssh_out && rm -rf $currdir/authorized_keys

set fil [open $host r]
while {[gets $fil ip ]>=0} {

    spawn ssh $user@$ip "rm -rf $home/.ssh/ && ssh-keygen -t rsa"
    expect {
        "*yes/no" {
            send "yes\r"
            exp_continue
        }
        "*assword" {
            send "$password\r"
            exp_continue
        }
        "*file in which to save the key*" {
            send "\n\r"
            send_user "$home/.ssh\r"
            exp_continue
        }
        "*Enter passphrase*" {
            send "\n\r"
            exp_continue
        }
        "*Enter same passphrase again*" {
            send "\n\r"
            exp_continue
        }
    }
    
    exec rm -rf $currdir/ssh_out
    spawn scp -r $user@$ip:$home/.ssh/id_rsa.pub ssh_out
    expect {
        "*yes/no" {
            send "yes\r"
            exp_continue
        }
        "*assword" {
            send "$password\r"
            exp_continue
        }
    }

    exec cat $currdir/ssh_out >> $currdir/authorized_keys
}
close $fil

exec rm -rf $currdir/ssh_out

set file [open $host r]
while {[gets $file ip ]>=0} {
    spawn scp -r $currdir/authorized_keys $user@$ip:$home/.ssh/
    expect {
        "*yes/no" {
            send "yes\r"
            exp_continue
        }
        "*assword" {
            send "$password\r"
            exp_continue
        }
    }
    
    spawn ssh $user@$ip "chmod 0600 $home/.ssh/authorized_keys "
    expect {
        "*yes/no" {
            send "yes\r"
            exp_continue
        }
        "*assword" {
            send "$password\r"
            exp_continue
        }
    }
}
close $file

启动脚本:

expect sshsetup.exp 免密用户 机器密码 免密用户文件位置如:/root sship.txt
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值