Python 利用pexpect和paramiko模塊進行遠程服務器的監控

一 模塊的安裝 java

   安裝pexpect模塊 python

        pip install pexpect 服務器

    安裝paramiko模塊 app

        yum install python-devel ssh

        pip install paramiko 測試

        注意:若是不安裝python-devel,則會報 spa

        error: command ‘gcc’ failed with exit status 1;這是由於缺乏python-dev的軟件包 線程

二 代碼示例     code

       pexpect代碼示例      orm

#!/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)
相關文章
相關標籤/搜索