前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python ssh 库 - paramiko and fabric

python ssh 库 - paramiko and fabric

作者头像
orientlu
发布2018-09-13 11:01:30
3.6K0
发布2018-09-13 11:01:30
举报
文章被收录于专栏:orientluorientlu

标题提到两个第三方库,都是可以实现在 python 中执行 ssh 命令。fabric 是在 paramiko 的基础上封装开发的。所以一般场景下 fabric 会更加容易使用。

paramiko

paramiko 最直接的是提供 SSHClient,呈现同服务器的一个会话,基本满足我们执行远程命令,文件上下传的操作。client 连接远端服务可以通过提供 key 或者秘钥的方式,如果 使用 ssh 秘钥登录(本地生成 ssh 公秘钥, 将公钥追加到服务器登录用户目录的 .ssh/authorized_keys 中),在建立连接时,将传递密码的参数改为传递秘钥参数既可。

先用 pip 安装 paramiko。

代码语言:javascript
复制
#!/usr/bin/env python
# coding=utf-8
# by orientlu

import paramiko

class ssh_client():

    def __init__(self, host=None,port=22, username=None, password=None, pkey_path=None, timeout=10):
        self.client = paramiko.SSHClient()
        """
        使用xshell登录机器,对于第一次登录的机器会提示允许将陌生主机加入host_allow列表
        需要connect 前调用,否则可能有异常。
        """
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        if password != None:
            self.client.connect(hostname=host,port=port, password=password, timeout=timeout)
        elif  pkey_path != None:
            """使用秘钥登录"""
            self.pkey = paramiko.RSAKey.from_private_key_file(pkey_path)
            self.client.connect(hostname=host,port=port,pkey=self.pkey, timeout=timeout)

        self.sftp = self.client.open_sftp()


    def run_cmd(self, cmd):
        _in, _out, _error = self.client.exec_command(cmd)
        return _out.read(),_error.read()

    def put_file(self, local, remote):
        return self.sftp.put(localpath=local, remotepath=remote)

    def get_file(self, local, remote):
        return self.sftp.get(localpath=local, remotepath=remote)

    def __del__(self):
        self.client.close()
        self.sftp.close()


if __name__ == "__main__":

    print("------ paramiko ssh client test -------")
    ## 密码登录
    #client = ssh_client(host='192.168.37.134', username='lcd', password='jklfds')
    ## 秘钥登录
    client = ssh_client(host='192.168.37.134', username='lcd',pkey_path="/home/lcd/.ssh/id_rsa")

    out, err = client.run_cmd('update')
    print("cO : %s"%out.strip('\n'))
    print("cE : %s"%err.strip('\n'))
    if len(err) != 0:
        print("cmd exec error")

    out, err = client.run_cmd('pwd; cd /home/')
    print("cO : %s"%out.strip('\n'))
    print("cE : %s"%err.strip('\n'))
    if len(err) != 0:
        print("cmd exec error")

    print client.get_file(local="./aa", remote="/home/lcd/.bashrc")
    print client.put_file(local="./aa", remote="/home/lcd/bb")

fabric

简单地介绍了 paramiko 后,稍微详细地来了解下 fabric 的使用方法和场景。支持 python(2.7 3.4)版本。

我直接在自己机器上通过 pip 安装,默认的版本是 Successfully installed fabric-2.1.3 然后发现在公司正常运行的脚本到这边是会报错的,import api 失败之类的问题,看了下原因,确实是版本不同导致的,坑爹。。。 可以通过 pip 指定安装旧版本

代码语言:javascript
复制
pip install fabric==1.14.0

1.14.0 版本的 fabric

通过 virtualenv 弄个低版本的临时环境,基本操作如下:

代码语言:javascript
复制
$ mkdir fabric_old-1   
$ cd ./fabric_old-1/
$ virtualenv --no-site-packages old_fabric
$ source old_fabric/bin/activate   ## 切到临时环境
$ pip install fabric==1.14.0            
# ...  fabric 版本为1.14.0 环境
$ deactivate

按照基本需求,封装了几个基本函数,分别是在本地和远程执行命令,上传和下载文件。

代码语言:javascript
复制
#!/usr/bin/env python
# coding=utf-8
# by orientlu
## fabric version 1.14.0
import fabric
from fabric.api import *

class ssh_client(object):

    def __init__(self, hosts_list=None, roles_list=None):

        env.hosts=[]
        env.passwords={}
        env.roledefs={}

        if hosts_list != None:
            for key in hosts_list.keys():
                env.hosts.append(key)
                env.passwords[key] = hosts_list[key]
        if roles_list != None:
            for key in roles_list.keys():
                env.roledefs[key] = roles_list[key]

    def _run_cmd(self, cmd, path=None):
        result = None
        if path != None:
            with cd(path):
                result = run(cmd, shell=False,warn_only=True,quiet=True)
        else:
            result = run(cmd, shell=False,warn_only=True,quiet=True)
        return result


    def remote_cmd(self, cmd, path=None,roles=None, is_parallel=0):
        if roles != None and len(roles) > 0:
            func=fabric.api.roles(*roles)(self._run_cmd)
        else:
            func=self._run_cmd

        if is_parallel == 1:
            func = fabric.api.parallel(func)

        result=execute(func,cmd)
        return result


    def local_cmd(self, cmd, path=None):
        result = None
        if path == None:
            path = './'
        with lcd(path):
            with settings(warn_only=True):
                result = local(cmd, capture=1)
        return result

    def _get_file(self, remote_path=None, file_name=None, local_path='./', alias=None):
        if remote_path != None and file_name != None:
            with cd(remote_path):
                with lcd(local_path):
                    if alias == None:
                        alias = file_name
                    result = get(file_name, alias)
        else:
            result = None
        return result

    def get_file(self, remote_path=None, file_name=None, local_path='./', alias=None, roles=None):
        if roles != None and len(roles) > 0:
            func=fabric.api.roles(*roles)(self._get_file)
        else:
            func=self._get_file

        result=execute(func,remote_path, file_name, local_path, alias)
        return result


    def _put_file(self, src_path='./', file_name=None, dst_path=None, alias=None):
        if file_name != None and dst_path != None:
            with lcd(src_path):
                with cd(dst_path):
                    if alias == None:
                        alias = file_name
                    result = put(file_name, alias)
        else:
            result = None
        return result

    def put_file(self, src_path='./', file_name=None, dst_path=None, alias=None, roles=None, is_parallel=0):
        if roles != None and len(roles) > 0:
            func=fabric.api.roles(*roles)(self._put_file)
        else:
            func=self._put_file

        if is_parallel == 1:
            func = fabric.api.parallel(func)

        result=execute(func,src_path, file_name, dst_path, alias)
        return result



if __name__ == "__main__":
    ## 主机登录信息
    hosts_list = {
            "lcd@192.168.37.134" : "jklfds",
            "lcd@192.168.37.135" : "jklfds",
            "lcd@192.168.37.136" : "jklfds",
            "lcd@192.168.37.137" : "jklfds",
    }

    ## 主机分组,按组执行任务
    roles_list = {
            "role1" : ["lcd@192.168.37.134"],
            "role2" : ["lcd@192.168.37.135", "lcd@192.168.37.137"],
            "role3" : ["lcd@192.168.37.134", "lcd@192.168.37.136"],
            "role4" : ["lcd@192.168.37.134"],
    }


    client = ssh_client(hosts_list, roles_list)

    result = client.remote_cmd("ls | wc -l", roles=["role1", "role4"])
    print result

    result = client.local_cmd("rm ./aa")
    print result

    client.get_file("/home/lcd", ".bashrc", local_path='./', alias='aa', roles=['role1'])

    client.put_file(file_name='aa', dst_path='/home/lcd', alias='cc', roles=['role1'])

参考

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.06.23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • paramiko
  • fabric
    • 1.14.0 版本的 fabric
    • 参考
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档