fabric添加多主机ssh互信

最近折腾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)

转载于:https://www.cnblogs.com/krainbow/p/fabric_ssh_copyid.html

要使用Fabric库连接SSH服务器,您可以按照以下步骤进行: 1. 安装Fabric库:您可以使用pip工具安装Fabric库,可以在终端中输入以下命令进行安装: ``` pip install fabric ``` 2. 引入Fabric库:在Python代码中,您需要使用import语句引入Fabric库,例如: ```python from fabric import Connection ``` 3. 创建连接对象:使用Connection()方法创建一个连接对象实例,例如: ```python c = Connection(host='your_hostname', user='your_username', connect_kwargs={'password': 'your_password'}) ``` 其中,`host`是SSH服务器的主机名或IP地址,`user`是登录用户名,`password`是登录密码。如果您使用的是SSH密钥登录,则可以使用`key_filename`参数指定密钥文件路径,例如: ```python c = Connection(host='your_hostname', user='your_username', connect_kwargs={'key_filename': '/path/to/your/keyfile'}) ``` 4. 执行命令:使用run()方法执行命令,例如: ```python result = c.run('ls -l') print(result.stdout) ``` 5. 关闭连接:使用close()方法关闭连接,例如: ```python c.close() ``` 以下是一个完整的示例代码: ```python from fabric import Connection # 创建连接对象实例 c = Connection(host='your_hostname', user='your_username', connect_kwargs={'password': 'your_password'}) # 执行命令 result = c.run('ls -l') # 输出结果 print(result.stdout) # 关闭连接对象 c.close() ``` 请注意,实际情况可能会因为服务器的实现方式而有所不同。如果您无法通过此方法成功连接服务器,请与服务器管理员联系以获取更多帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值