Python通過ssh連接服務器並執行命令


[本文出自天外歸雲的博客園]

腳本示例如下:

# coding:utf-8
import time,paramiko,re,StringIO

def exec_shell(command):
    '''
        command:傳入的要執行的shell命令
    '''
    f = StringIO.StringIO()
    header_match = '(\[.+?@.+?\s.+?\]\$)'
    ssh.send(command+'\n')
    while True:
        out = ssh.recv(1024)
        print out,
        f.write(out)
        header_list = re.findall(header_match, out)
        if header_list and out.strip().endswith(header_list[-1]):
            break
    return f

def check_ip(content):
    '''
        從content中取出所有符合xx.120.xx.xx格式的ip地址(xx代表任意多數字)並返回
    '''
    ips = re.findall('\d+\.120\.\d+\.\d+',content)
    return ips

if __name__ == '__main__':
    '''
        host:對應要連接的服務器ip
        port:對應連接服務器的端口
        username:對應訪問服務器的用戶名
    '''
    host = '10.120.143.70'
    port = 8822
    username = 'bjlantianyou'
    '''
        key_file為secureCRT對應的OpenSSH格式的私鑰文件
        可以在secureCRT的'Tools->Convert Private Key to OpenSSH Format...'選擇相應的私鑰文件轉化為OpenSSH格式
        例如:在Windows下保存到'E:\keys\'路徑下,保存文件名為'id_rsa'
    '''
    key_file = 'E:\\keys\\id_rsa'
    key = paramiko.RSAKey.from_private_key_file(key_file)
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    s.connect(host, port, username, pkey=key)
    ssh = s.invoke_shell()
    '''
        下面對應在secureCRT上執行命令的過程
    '''
    exec_shell('cd /home/project/api.winyyg.com')
    out = exec_shell('ls')
    ips = check_ip(out.getvalue())
    exec_shell('cat '+ips[0]+'/log/duobao.log')

注意:緩沖區為空的情況下,ssh.recv(1024)會hang住。

可以進一步利用這個方法做一個自動化過濾log的工具或平台。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM