但是在實際工作中,往往機器很多,如果一台一台的去建立互信,則也需要耗費巨大的人力。
在網上看到乙個自動化批量建立互信的指令碼,在此分享給大家。
在主機上建立sh檔案,名稱隨意,然後在檔案中輸入以下內容:
#!/bin/sh新建主機列表檔案,一行乙個需要建立互信的ip。dest_user=$1
password=$2
hosts_file=$3
if [ $# -ne 3 ]; then
echo
"usage:
"echo
"$0 remoteuser remotepassword hostsfile
"exit 1fi
ssh_dir=~/.ssh
script_prefix=./tmp
echo *************************==#
1. prepare directory .ssh
mkdir
$ssh_dir
chmod
700$ssh_dir
# 2. generat ssh
keytmp_script=$script_prefix.sh
echo
"#!/usr/bin/expect
">$tmp_script
echo
"spawn ssh-keygen -b 1024 -t rsa
">>$tmp_script
echo
"expect *key*
">>$tmp_script
echo
"send \r
">>$tmp_script
if [ -f $ssh_dir/id_rsa ]; then
echo
"expect *verwrite*
">>$tmp_script
echo
"send y\r
">>$tmp_script
fiecho
"expect *passphrase*
">>$tmp_script
echo
"send \r
">>$tmp_script
echo
"expect *again:
">>$tmp_script
echo
"send \r
">>$tmp_script
echo
"interact
">>$tmp_script
chmod +x $tmp_script
/usr/bin/expect $tmp_script
rm$tmp_script
# 3. generat file
authorized_keys
cat $ssh_dir/id_rsa.pub>>$ssh_dir/authorized_keys
# 4. chmod
600for
file
authorized_keys
chmod
600 $ssh_dir/authorized_keys
echo *************************==#
5. copy all files to other hosts
for ip in $(cat
$hosts_file)
doif [ "
x$ip
" != "
x" ]; then
echo -------------------------tmp_script=$.$ip.sh
# check known_hosts
val=`ssh-keygen -f $ip`
if [ "
x$val
" == "
x" ]; then
echo
"$ip not in $ssh_dir/known_hosts, need to add
"val=`ssh-keyscan $ip 2>/dev/null
`
if [ "
x$val
" == "
x" ]; then
echo
"ssh-keyscan $ip failed!
"else
echo $val>>$ssh_dir/known_hosts
fifi
echo
"copy $ssh_dir to $ip
"echo
"#!/usr/bin/expect
">$tmp_script
echo
"spawn scp -r $ssh_dir $dest_user@$ip:~/
">>$tmp_script
echo
"expect *assword*
">>$tmp_script
echo
"send $password\r
">>$tmp_script
echo
"interact
">>$tmp_script
chmod +x $tmp_script
#echo
"/usr/bin/expect $tmp_script
" >$tmp_script.do
#sh $tmp_script.do&
/usr/bin/expect $tmp_script
rm$tmp_script
echo
"copy done."fi
done
echo
done.
示例如下:
192.168.1.2執行剛才新建的.sh檔案,指令碼接受三個引數,遠端機器使用者名稱、密碼和host檔名(相對路徑或絕對路徑均可)。192.168.1.3
192.168.1.4
192.168.1.5
例如:
指令碼會生成pub公鑰檔案,並將公鑰拷貝至指定主機。
linux 批量ssh認證
redis01 root cd ssh bash cd ssh no such file or directory redis01 root pwd root redis01 root cd ssh redis01 root ssh ls known hosts redis01 root ssh l...
linux 批量建立使用者
root jhoa cat expect.sh while read line douser echo line awk ip echo line awk passwd echo line awk expect expect2.exp user ip passwd done root jhoa ca...
Linux 虛擬機器自動批量配置ssh免密登陸
需要注意 各台機器需要安裝expect。假如連線外網則可以使用yum安裝。yum install expect.假如沒有連線外網的條件,也可以使用rpm包進行安裝 指令碼編寫如下 其中第乙個引數為要設定ssh的使用者名稱,這裡為spark 第二個引數為使用者對應的密碼 第三個引數為要設定互通ssh的...