Python 利用pexpect和paramiko模块进行远程服务器的监控-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

Python 利用pexpect和paramiko模块进行远程服务器的监控

简介:

一 模块的安装

   安装pexpect模块

        pip install pexpect

    安装paramiko模块

        yum install python-devel

        pip install paramiko

        注意:如果不安装python-devel,则会报

        error: command ‘gcc’ failed with exit status 1;这是因为缺少python-dev的软件包

二 代码示例    

       pexpect代码示例     

#!/usr/bin/python
# encoding=utf-8
# Filename: pexpect_test.py
import pexpect
def sshCmd(ip, passwd, cmd):
    ret = -1
    ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
    try:
        i = ssh.expect(['password:', 'continue connecting(yes/no)?'], timeout=5)
        if i == 0:
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes\n')
            ssh.expect('password:')
            ssh.sendline(passwd)
        ssh.sendline(cmd)
        r = ssh.read()
        print r
        ret = 0
    except pexpect.EOF:
        print "EOF"
        ret = -1
    except pexpect.TIMEOUT:
        print "TIMEOUT"
        ret = -2
    finally:
        ssh.close()
    return ret

sshCmd('xxx.xxx.xxx.xxx','xxxxxx','ls /root')
paramiko代码示例

注意:必须要增加client.load_system_host_keys()此句,否则报如下错误:

unbound method missing_host_key() must be called with AutoAddPolicy instance as first argument (got SSHClient instance instead)

#!/usr/bin/python
# encoding=utf-8
# Filename: paramiko_test.py
import datetime
import threading
import paramiko

def sshCmd(ip, username, passwd, cmds):
    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        client.connect(ip, 22, username, passwd, timeout=5)
        for cmd in cmds:
            stdin, stdout, stderr = client.exec_command(cmd)
            lines = stdout.readlines()
            # print out
            for line in lines:
                print line,
        print '%s\t 运行完毕\r\n' % (ip)
    except Exception, e:
        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
    finally:
        client.close()

#上传文件       
def uploadFile(ip,username,passwd):
    try:
        t=paramiko.Transport((ip,22))
        t.connect(username=username,password=passwd)
        sftp=paramiko.SFTPClient.from_transport(t)
        remotepath='/root/main.py'
        localpath='/home/data/javawork/pythontest/src/main.py'
        sftp.put(localpath,remotepath)
        print '上传文件成功'
    except Exception, e:
        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
    finally:
        t.close()

#下载文件 
def downloadFile(ip,username,passwd):
    try:
        t=paramiko.Transport((ip,22))
        t.connect(username=username,password=passwd)
        sftp=paramiko.SFTPClient.from_transport(t)
        remotepath='/root/storm-0.9.0.1.zip'
        localpath='/home/data/javawork/pythontest/storm.zip'
        sftp.get(remotepath,localpath)
        print '下载文件成功'
    except Exception, e:
        print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
    finally:
        t.close()  
        
if __name__ == '__main__':
    # 需要执行的命令列表
    cmds = ['ls /root', 'ifconfig']
    # 需要进行远程监控的服务器列表
    servers = ['xxx.xxx.xxx.xxx']
     
    username = "root"
    passwd = "xxxxxx"
    threads = []
    print "程序开始运行%s" % datetime.datetime.now()
    # 每一台服务器创建一个线程处理
    for server in servers:
        th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))
        th.start()
        threads.append(th)
         
    # 等待线程运行完毕
    for th in threads:
        th.join()
         
    print "程序结束运行%s" % datetime.datetime.now()
    
    #测试文件的上传与下载
    uploadFile(servers[0],username,passwd)
    downloadFile(servers[0],username,passwd)

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章
最新文章
相关文章