zoukankan      html  css  js  c++  java
  • paramiko

    一、paramiko介绍

    用于远程连接服务器,使用ssh协议。ssh是用于计算机之间加密登陆的网络协议,协议就是端对端的一种通讯交互。
    使用条件:python 2.6+/3.3+

    二、安装

    linux:

    2.1 Linux系统底层需要安装的环境

    yum -y install gcc gcc-c++ kernel-devel

    yum -y install python-devel libxslt-devel libffi-devel openssl-devel

    yum install -y gcc make patch gdbm-devel openssl-devel sqlite-devel readline-devel zlib-devel bzip2-devel

    2.2 paramiko关联包

    paramiko(cryptography和pyasn1)

    cryptography(enum34,idna,ipaddress,asn1crypto,six,cffi)

    cffi(pycparser)
    1.paramiko
    2.cryptography(需要安装yum install openssl-devel,依赖cryptography)
      3.enum34
      4.idna
      5.ipaddress
      6.asn1crypto
      8.six
      10.cffi(需要安装yum install -y libffi libffi-devel,需要libffi编译环境,依赖pycparser)
           9.pycparser
    7.pyasn1
    10.bcrypt(依赖cffi,six)(paramiko2.1.1不需要安装)
    12.pynacl(依赖cffi,six)(paramiko2.1.1不需要安装)

    pip install paramiko的时候容易出现如下错误:
    error: command 'gcc' failed with exit status 1
    解决方法:
    yum -y install gcc gcc-c++ kernel-devel
    yum -y install python-devel libxslt-devel libffi-devel openssl-devel
    yum install -y mysql-devel python-devel python-setuptools
     
    pip install paramiko==2.1.1   #会自动安装如下包

    asn1crypto (0.24.0)
    bcrypt (3.1.4)
    cffi (1.11.5)        #此包是为了让python调用C代码,为了能让cffi安装成功,必须安装gcc和libffi-devel
    cryptography (2.1.4)
    enum34 (1.1.6)
    idna (2.6)
    ipaddress (1.0.22)
    paramiko (2.1.1)
    pyasn1 (0.4.2)
    pycparser (2.18)
    PyNaCl (1.2.1)
    six (1.11.0)

    关于ciffi ,libffi的使用和安装都是十分混乱的,所以cpython拥有自己的拷贝避免依赖外部其他包。cffi对于windows系统是这样,但是对于其他拥有自己的libffi的系统则比较麻烦

    • virtualenv ~/venv
    • cd ~/path/to/sources/of/cffi
    • ~/venv/bin/python setup.py build --force # forcing a rebuild to make sure
    • ~/venv/bin/python setup.py install

    windows:

    paramiko的安装需要依赖于`PyCrypto` 这个库中有许多的加密算法。

    1)下载PyCrypto

    http://www.voidspace.org.uk/python/modules.shtml#pycrypto

    直接从链接上下载已与系统对应的pycrypto版本,点击安装执行下一步下一步即可

    若在安装的时候,出现获取不到python路径的问题,则用如下办法解决

    #   
    # script to register Python 2.0 or later for use with win32all   
    # and other extensions that require Python registry settings   
    #   
    # written by Joakim Loew for Secret Labs AB / PythonWare   
    #   
    # source:   
    # http://www.pythonware.com/products/works/articles/regpy20.htm   
    #   
    # modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html   
       
    import sys  
       
    from _winreg import *  
       
    # tweak as necessary   
    version = sys.version[:3]  
    installpath = sys.prefix  
       
    regpath = "SOFTWARE\Python\Pythoncore\%s\" % (version)  
    installkey = "InstallPath"  
    pythonkey = "PythonPath"  
    pythonpath = "%s;%s\Lib\;%s\DLLs\" % (  
        installpath, installpath, installpath  
    )  
       
    def RegisterPy():  
        try:  
            reg = OpenKey(HKEY_CURRENT_USER, regpath)  
        except EnvironmentError as e:  
            try:  
                reg = CreateKey(HKEY_CURRENT_USER, regpath)  
                SetValue(reg, installkey, REG_SZ, installpath)  
                SetValue(reg, pythonkey, REG_SZ, pythonpath)  
                CloseKey(reg)  
            except:  
                print "*** Unable to register!"  
                return  
            print "--- Python", version, "is now registered!"  
            return  
        if (QueryValue(reg, installkey) == installpath and  
            QueryValue(reg, pythonkey) == pythonpath):  
            CloseKey(reg)  
            print "=== Python", version, "is already registered!"  
            return  
        CloseKey(reg)  
        print "*** Unable to register!"  
        print "*** You probably have another Python installation!"  
       
    if __name__ == "__main__":  
        RegisterPy()  

    然后执行此文件

    然后即可正常安装了

    在python GUI中输入 import Crypto测试是否安装成功

    2)下载paramiko

    cmd进入C:Python27Libsite-packages中执行pip install paramiko

    ----------------------------------------------------------------------------------------------------------------------------------

    讲解paramiko包

    paramiko包有有几个重要的类文件,比如Channel类、Client类、Message类、Packetizer类、Transport类

    Transport


    transport.py文件中包含class Transport()也包含其他class A,B,C...

    在程序中import paramiko后,直接可以使用transport.py中的类,即x=paramiko.Transport()

    步骤一 __init__(sock,其他可选默认参数) 初始化,建立一个socket, 还没有开启SSH session trans=paramiko.Transport((192.168.1.1, 22))
    步骤二 connet(username,password) 连接 trans.connect(username='xxx',password='xx')
     2 start_client() 开启客户端session  
      start_server() 开启服务端session  
      auth_password(username,password)  验证  trans.auth_password(username='xx',password='xx')
      open_session()  打开一个通道  channel=trans.open_session()
      open_channel()  同上  
      get_pty()  获取终端  channel.get_pty()
      invoke_shell()  激活终端  channel.invoke_shell()
      settimeout()   设置超时时间  channel.settimeout(5)

    __init__(sock, 其它默认参数)  初始化,建立一个socket

    使用:

    连接服务器

    方式一:

    方式二:

    paramiko的API 官方文档:http://docs.paramiko.org/en/2.4/

     t=paramiko.Transport(ip,port)

    t.connect(username,pasword)

    t.open_session()

    t.invoke_shell()

    t.settimeout()

    t.send()

    如果用paramiko遇到了connection莫名自己关闭的情况,参考下面的代码

    def create_a_conn(ip_addr, port, username, password):
      '''
      creat a conn to router using paramiko.SSHClient()
      '''
      conn_session = paramiko.SSHClient()
      conn_session.load_system_host_keys()
      conn_session.connect(ip_addr, port, username, password, look_for_keys = Fals
    e, allow_agent = False)
      conn = conn_session.invoke_shell()# to keep the session go on
      conn.keep_this = conn_session
    
      time.sleep(1)
      conn.send("terminal length 0
    ")
      time.sleep(1)
    
      if conn.recv_ready():
      conn.recv(65535)
    
      return conn

    注意conn.keep_this = conn_session 这一句是解决connection莫名自己关闭的情况的关键

    没有这一句会报如下错误

    File "/home/hsun/applied_python/local/lib/python2.7/site-packages/paramiko/channel.py", line 715, in send
      return self._send(s, m)
      File "/home/hsun/applied_python/local/lib/python2.7/site-packages/paramiko/channel.py", line 1075, in _send
      raise socket.error('Socket is closed')
    socket.error: Socket is closed
  • 相关阅读:
    PAT 天梯赛 L1-048. 矩阵A乘以B 【数学】
    PAT 天梯赛 L1-047. 装睡 【水】
    PAT 天梯赛 L1-047. 装睡 【水】
    PAT 天梯赛 L1-045. 宇宙无敌大招呼 【水】
    PAT 天梯赛 L1-045. 宇宙无敌大招呼 【水】
    PAT 天梯赛 L1-044. 稳赢 【循环】
    PAT 天梯赛 L1-044. 稳赢 【循环】
    PAT 天梯赛 L1-042. 日期格式化 【水】
    PAT 天梯赛 L1-042. 日期格式化 【水】
    PAT 天梯赛 L1-041. 寻找250 【水】
  • 原文地址:https://www.cnblogs.com/zz27zz/p/7903955.html
Copyright © 2011-2022 走看看