最近折腾fabric,把服务器ssh互信用fabric写了一遍,单向互信,master可以无密码访问client,具体如下:
执行:fab -f ./copyrsa.py allsshkey 即可,如果服务器多的话,还可以增加@parallel等参数来优化运行效率。
[root@kvm02_web02 fabric]# cat copyrsa.py
from fabric.api import *
env.roledefs = {
'master':['10.168.32.107'],
'client':['10.168.32.106',
'10.168.32.110',
'10.168.32.111'],
}
env.hosts = [
'root@10.168.32.106',
'root@10.168.32.110',
'root@10.168.32.111',
]
env.passwords = {
'root@10.168.32.106:22': 'passwd1',
'root@10.168.32.110:22': 'passwd1',
'root@10.168.32.111:22': 'passwd1',
}
@roles('master')
def get_sshkey_rsa():
local("if [ ! -f ~/.ssh/id_rsa ]; then ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa;fi")
@roles('client')
def copy_id(file='~/.ssh/id_rsa.pub'):
put(file, "/tmp/id_rsa.pub")
try:
run("if [ ! -d ~/.ssh ]; then mkdir -p ~/.ssh; fi")
run("if [ ! -f ~/.ssh/authorized_keys ]; then cp /tmp/id_rsa.pub ~/.ssh/authorized_keys && chmod 0600 ~/.ssh/authorized_keys; fi")
run("cat ~/.ssh/authorized_keys >> /tmp/id_rsa.pub && sort -u /tmp/id_rsa.pub > ~/.ssh/authorized_keys")
finally:
run("rm -f /tmp/id_rsa.pub")
def allsshkey():
execute(get_sshkey_rsa)
execute(copy_id)