zoukankan      html  css  js  c++  java
  • 基于 Paramiko 的 SSH 通讯类

    # -*- coding: UTF-8 -*-
    import paramiko
    import time

    ##################################################################
    '''类名称: SSHCommunication
    描述:SSH通讯类
    作者:Sid Zhang(autopenguin)'''
    ##################################################################
    class SSHCommunication():
    def __init__(self):
    self.client = paramiko.SSHClient()
    ##################################################################
    '''方法名称: Logon
    参数:HostIP->登录主机IP【字符串】
    SSHPort->SSH登录端口号【数字】
    Username->登录用户名【字符串】
    Password->登录密码【字符串】
    返回值:None
    描述:SSH登录方法'''
    ##################################################################
    def Logon(self, HostIP, SSHPort, Username, Password):
    self.client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
    self.client.connect(HostIP, SSHPort, Username, Password)
    self.chan = self.client.invoke_shell()
    self.chan.settimeout(120)
    ##################################################################
    '''函数名称: Send
    参数:Cmds->待发送的命令列表【字符串列表】
    返回值:None
    描述:发送命令方法'''
    ##################################################################
    def Send(self, Cmds = []):
    for Cmd in Cmds:
    while not self.chan.send_ready():
    time.sleep(0.1)
    self.chan.send(Cmd + ' ')
    print 'Execute Command: ' + Cmd
    ##################################################################
    '''函数名称: SendWithoutReceive
    参数:Cmds->待发送的命令列表【字符串列表】
    返回值:None
    描述:发送命令且无须接收结果方法'''
    #################################################################
    def SendWithoutReceive(self, Cmds=[]):
    self.Send(Cmds)
    self.Receive()
    ##################################################################
    '''函数名称: Receive
    参数:None
    返回值:命令执行输出
    描述:接收命令输出方法'''
    ##################################################################
    def Receive(self):
    while not self.chan.recv_ready():
    time.sleep(0.1)
    CommandOut = self.chan.recv(1024000)
    CommandOutAll = CommandOut
    while not (CommandOut.endswith('x1b[mx0f') or CommandOut.endswith('> ') or CommandOut.endswith('$') or CommandOut.endswith('# ')):
    while not self.chan.recv_ready():
    time.sleep(0.1)
    CommandOut = self.chan.recv(102400)
    CommandOutAll = CommandOutAll + CommandOut
    return CommandOutAll
    ##################################################################
    '''函数名称: Logout
    参数:None
    返回值:None
    描述:SSH登出方法'''
    ##################################################################
    def Logout(self):
    self.chan.close()
  • 相关阅读:
    读书笔记:《与爱因斯坦月球漫步》
    在职工象棋赛上弃子拿下一盘
    桥牌笔记:精准叫牌法摘要
    桥牌笔记:探查牌型分布
    在64位环境下开发程序时常遇到的一个错误:无法加载文件或程序集
    我的记忆图像编码
    【转载】新闻周刊:《2012:31个让你变聪明的方法》
    【转译】希望将来孩子评价父亲的35句话
    桥牌笔记:安全打法,保持将牌控制
    被Html的Button标签耍了一次
  • 原文地址:https://www.cnblogs.com/autopenguin/p/6133017.html
Copyright © 2011-2022 走看看