您的位置:首页 > 其它

ssh 免密码登录实现批量处理

2016-07-25 16:29 260 查看
搭建集群的时候ssh 免密码登录是一个问题以下脚本将实现批量处理

文件1主机名:host

17.19.18.11:123
17.19.18.12:123

文件2:ssh_setup.py

#!/usr/bin/python

import subprocess
import os

file_dir='/home/hosts'

with open(file_dir) as data:
for each_line in data.readlines():
if each_line != '':
(ip,passwd)=each_line.split(':',2)
print('./sshkey.exp '+ip+' root '+passwd.strip('\n')+' | grep ssh-rsa >> ~/.ssh/authorized_keys')
subprocess.Popen('./sshkey.exp '+ip+' root '+passwd.strip('\n')+' | grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
#  subprocess.Popen('./sshkey.exp '+ip+' root '+passwd+' \\| grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
else:
pass
subprocess.Popen('chmod 755 ~/.ssh/authorized_keys',shell=True)
#subprocess.Popen('/home/ssh_distribute.py',shell=True)


文件3:ssh_distribute.py

#!/usr/bin/python

import subprocess
import os

file_dir='/home/hosts'

with open(file_dir) as data:
for each_line in data.readlines():
if each_line != '':
(ip,passwd)=each_line.split(':',2)
print('./noscp.exp ~/.ssh/authorized_keys '+ip+':~/.ssh '+'root '+passwd.strip('\n'))
subprocess.Popen('./noscp.exp ~/.ssh/authorized_keys '+ip+':~/.ssh '+'root '+passwd.strip('\n'),shell=True)
#  subprocess.Popen('./sshkey.exp '+ip+' root '+passwd+' \\| grep ssh-rsa >> ~/.ssh/authorized_keys',shell=True)
else:
pass
#subprocess.Popen('chmod 755 ~/.ssh/authorized_keys',shell=True)


文件4:noscp.exp

#!/usr/bin/expect

#noscp.exp

if {$argc<4} {
puts stderr "Usage: $argv0 localfile  remotefile user passwd "
exit 1
}

set localfile [ lindex $argv 0 ]
set remotefile  [ lindex $argv 1 ]
set user  [ lindex $argv 2 ]
set pwd  [ lindex $argv 3 ]

set timeout 30

spawn scp ${localfile}  ${user}@${remotefile}

expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}

expect eof


文件5:sshkey.exp

#!/usr/bin/expect

#sshkey.exp

if {$argc<3} {
puts stderr "Usage: $argv0 host  user  passwd "
exit 1
}

set host [ lindex $argv 0 ]
set user  [ lindex $argv 1 ]
set pwd  [ lindex $argv 2 ]
set timeout 30
#spawn ssh  ${user}@${host} "rm -rf ~/.ssh/id_rsa*"
#
#expect {
# "*yes/no" { send "yes\r"; exp_continue }
# "*password:" { send "$pwd\r"; exp_continue  }
#}

spawn ssh  ${user}@${host} "ssh-keygen -t rsa"

expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r"; exp_continue  }
"Enter file in which to save the key*" { send "\n\r"; exp_continue }
"Overwrite*" { send "y\n"; exp_continue }
"Enter passphrase (empty for no passphrase):" { send "\n\r"; exp_continue }
"Enter same passphrase again:" { send "\n\r" }
}

spawn ssh  ${user}@${host} "cat ~/.ssh/id_rsa.pub"
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r"  }
}

expect eof


步骤:

1.将此文件夹内文件拷贝到/home目录下
2.host内添加所有待处理的 ip:密码
3.安装expect 如果没有 yum install expect
4.执行./ssh_setup.py
5.执行./ssh_distribute.py
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: