python利用paramiko連接遠程服務器執行命令

python中的paramiko模塊是用來實現ssh連接到遠程服務器上的庫,在進行連接的時候,可以用來執行命令,也可以用來上傳文件。

1、得到一個連接的對象

在進行連接的時候,可以使用如下的代碼:

 

def connect(host):
    'this is use the paramiko connect the host,return conn'
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
#        ssh.connect(host,username='root',allow_agent=True,look_for_keys=True)
        ssh.connect(host,username='root',password='root',allow_agent=True)
        return ssh
    except:
        return None

在connect函數中,參數是一個主機的IP地址或者是主機名稱,在執行這個方法之後,如果成功的連接到服務器,那麼就會返回一個sshclient對象。

 

第一步是建立一個SSHClient的對象,然後設置ssh客戶端允許連接不在know_host文件中的機器,然後就嘗試連接服務器,在連接服務器的時候,可以使用兩種方式:一種方式是使用祕鑰的方式,也就是參數look_for_keys,這裏用設置密碼尋找,也可以直接使用密碼的方式,也就是直接使用參數password,從而最後返回一個連接的對象。

 

2、 獲取設置的命令

在進行paramiko連接之後,那麼必須要得到需要執行的命令,如下代碼所示:

 

def command(args,outpath):
    'this is get the command the args to return the command'
    cmd = '%s %s' % (outpath,args)
    return cmd


在參數中,一個是args,一個outpath,args表示命令的參數,而outpath表示爲可執行文件的路徑,例如/usr/bin/ls -l。在其中outpath也就是/usr/bin/ls ,而參數爲-l

 

這個方法主要是用來組合命令,將分開的參數作爲命令的一部分進行組裝。


3、 執行命令

在連接過後,可以進行直接執行命令,那麼就有了如下的函數:

 

def exec_commands(conn,cmd):
    'this is use the conn to excute the cmd and return the results of excute the command'
    stdin,stdout,stderr = conn.exec_command(cmd)
    results=stdout.read()
    return results

在此函數中,傳入的參數一個爲連接的對象conn,一個爲需要執行的命令cmd,最後得到執行的結果,也就是stdout.read(),最後返回得到的結果

 

 

4、 上傳文件

在使用連接對象的時候,也可以直接進行上傳相關的文件,如下函數:

 

def copy_moddule(conn,inpath,outpath):
    'this is copy the module to the remote server'
    ftp = conn.open_sftp()
    ftp.put(inpath,outpath)
    ftp.close()
    return outpath


此函數的主要參數爲,一個是連接對象conn,一個是上傳的文件名稱,一個上傳之後的文件名稱,在此必須寫入完整的文件名稱包括路徑。

 

做法主要是打開一個sftp對象,然後使用put方法進行上傳文件,最後關閉sftp連接,最後返回一個上傳的文件名稱的完整路徑

5、 執行命令得到結果

最後就是,執行命令,得到返回的結果,如下代碼:

 

def excutor(host,outpath,args):
    conn = connect(host)
    if not conn:
        return [host,None]
    exec_commands(conn,'chmod +x %s' % outpath)
    cmd =command(args,outpath)
    result = exec_commands(conn,cmd)
    print '%r' % result
    result = json.loads(result)
    return [host,result]

首先,進行連接服務器,得到一個連接對象,如果連接不成功,那麼返回主機名和None,表示沒有連接成功,如果連接成功,那麼修改文件的執行權限,從而可以執行文件,然後得到執行的命令,最後,進行執行命令,得到結果,將結果用json格式表示返回,從而結果能得到一個美觀的json格式,最後和主機名一起返回相關的信息

 

 

6、 測試代碼

測試代碼如下:

 

if __name__ == '__main__':
    print json.dumps(excutor('192.168.1.165','ls',' -l'),indent=4,sort_keys=True)
    print copy_module(connect('192.168.1.165'),'kel.txt','/root/kel.1.txt')
    exec_commands(connect('192.168.1.165'),'chmod +x %s' % '/root/kel.1.txt')

第一步測試命令執行,第二步測試上傳文件,第三部測試修改上傳文件的權限。

 

 

完整代碼如下:

 

#!/usr/bin/env python
import json
import paramiko

def connect(host):
    'this is use the paramiko connect the host,return conn'
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
#        ssh.connect(host,username='root',allow_agent=True,look_for_keys=True)
        ssh.connect(host,username='root',password='root',allow_agent=True)
        return ssh
    except:
        return None

def command(args,outpath):
    'this is get the command the args to return the command'
    cmd = '%s %s' % (outpath,args)
    return cmd

def exec_commands(conn,cmd):
    'this is use the conn to excute the cmd and return the results of excute the command'
    stdin,stdout,stderr = conn.exec_command(cmd)
    results=stdout.read()
    return results

def excutor(host,outpath,args):
    conn = connect(host)
    if not conn:
        return [host,None]
    #exec_commands(conn,'chmod +x %s' % outpath)
    cmd =command(args,outpath)
    result = exec_commands(conn,cmd)
    result = json.dumps(result)
    return [host,result]
def copy_module(conn,inpath,outpath):
    'this is copy the module to the remote server'
    ftp = conn.open_sftp()
    ftp.put(inpath,outpath)
    ftp.close()
    return outpath


if __name__ == '__main__':
    print json.dumps(excutor('192.168.1.165','ls',' -l'),indent=4,sort_keys=True)
    print copy_module(connect('192.168.1.165'),'kel.txt','/root/kel.1.txt')
    exec_commands(connect('192.168.1.165'),'chmod +x %s' % '/root/kel.1.txt')


主要就是使用python中的paramiko模塊通過ssh連接linux服務器,然後執行相關的命令,並且將文件上傳到服務器。

 

公衆號:SRE藝術

 

 

 

 

 

 

 

發佈了213 篇原創文章 · 獲贊 78 · 訪問量 76萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章