python fabric

python fabric

该神器可以完成远程登录linux系统,并执行脚本等功能
安装

pip install fabric

使用
通过fabric.Connection方法连接服务器:

conn = fabric.Connection(host , user = ‘root’,port = 22, config = None, geteway = None, connect_kwargs={“password”: “123456”})

Connection参数的含义:

  def __init__(
    self,
    host,                       #主机ip
    user=None,                  #用户名
    port=None,                  #ssh端口,默认是22
    config=None,                #登录配置文件
    gateway=None,               #连接网关
    forward_agent=None,         #是否开启agent forwarding
    connect_timeout=None,       #设置超时
    connect_kwargs=None,        #设置 密码登录connect_kwargs={"password": "123456"}) 还是 密钥登录connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
    inline_ssh_env=None,      
    )

通过fabric安装软件
下面通过一段代码实现在Ubuntu上批量卸载docker,顺序取走列表中的ip。

import fabric

def docker_install():
    for host in ['10.224.106.21']:
        conn = fabric.Connection(host , user = 'root', connect_kwargs={<!-- -->"password": "123456"})
        print("%s:" % host)
        conn.run("echo Y|apt-get remove docker.io")
docker_install()

cnn获取Connetction对象后,有很多属性方法可以使用,介绍下几个常用的:

run:                #执行远程命令,如:run('uname -a')

cd:                 #切换远程目录,如:cd('/root');   with conn.cd('/root'):继承这个状态

put:                #上传本地文件到远程主机,如:put('/root/test.py','/root/test.py')

get:                 #获取服务器上文件,如:get('/root/project/test.log')

sudo:               #sudo方式执行远程命令,如:sudo('service docker start')

全部属性:

[‘cd’, ‘clear’, ‘client’, ‘close’, ‘config’, ‘connect_kwargs’, ‘connect_timeout’, ‘create_session’, ‘cwd’, ‘derive_shorthand’, ‘forward_agent’, ‘forward_local’, ‘forward_remote’, ‘from_data’, ‘from_v1’, ‘gateway’, ‘get’, ‘get_gateway’, ‘host’, ‘is_connected’, ‘local’, ‘open’, ‘open_gateway’, ‘original_host’, ‘pop’, ‘popitem’, ‘port’, ‘prefix’, ‘put’, ‘resolve_connect_kwargs’, ‘run’, ‘setdefault’, ‘sftp’, ‘ssh_config’, ‘sudo’, ‘transport’, ‘update’, ‘user’]

上一篇:洛谷p2895


下一篇:【Spring Boot整合视图层技术】