2019独角兽企业重金招聘Python工程师标准>>>
fabric作为一种强大的运维工具,可以让部署运维轻松很多,最简单的fabric使用,首先设置env.user,env.port,env.hosts,env.password,如:
#coding:utf8
from fabric.api import *
#用户名
env.user = "shikanon"
#中转ip,堡垒机
env.gateway = "10.17.35.92"
env.port = 12303
env.hosts = ["192.168.6.%d"%i for i in range(2,11)]
#密码
env.password = "shikanon_123456"
这样就配置好了集群,但通常情况下为了安全堡垒机和各机器的用户名、端口号、密码都是不同的,那么需要有针对性设置,在fabric中用env.hosts和env.password组合就可以了,不过需要注意的是原来的ip形式需要全部改为user@host:port这种形式,代码如下
#需要以user@host:port填写
env.gateway = "shikanon@183.3.169.134:12020"
env.hosts = ["shikanon@183.3.169.134:12020", "root@192.168.0.171:22", "root@192.168.0.181:22"]
#可以定义不同的密码
env.passwords = {"shikanon@183.3.169.134:12020":"shikanon_123456","root@192.168.0.171:22":"12shikanon_3456","root@192.168.0.181:22":"1234shikanon_56"}
#下面是rsa免登录设置
#
def create_keygen():with settings(warn_only=True):run("rm -rf shikanon/.ssh")with settings(warn_only=True):run("mkdir -p shikanon/.ssh")with settings(warn_only=True):result = run(r"ssh-keygen -t rsa -P '' -f ~/shikanon/.ssh/id_rsa")def get_ras_id():get("~/shikanon/.ssh/id_rsa.pub","./rsa/rsa_%s_id_rsa.pub"%(env.host))@runs_once
def zip():local("zip -r authorized_keys.zip rsa/")def clean():run("rm -rf ~/shikanon/")def upload():run("rm -f authorized_keys.zip")put("authorized_keys.zip","~/shikanon/")with settings(warn_only=True):run("unzip ~/shikanon/authorized_keys.zip -d ~/shikanon/.ssh")rsa_files = run("ls ~/shikanon/.ssh/rsa/")for commandline in rsa_files.split("\r\n"):for rsa_file in commandline.split(" "):if rsa_file:print("rsa_file:",rsa_file)run("cat ~/shikanon/.ssh/rsa/%s >> ~/shikanon/.ssh/authorized_keys"%rsa_file)
以上是一个设置ssh免密码登陆的脚本