python使用paramiko串連遠程伺服器執行命令的範例程式碼

來源:互聯網
上載者:User
下面小編就為大家帶來一篇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 pythonimport jsonimport paramikodef 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 Nonedef command(args,outpath):  'this is get the command the args to return the command'  cmd = '%s %s' % (outpath,args)  return cmddef 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 resultsdef 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 outpathif __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伺服器,然後執行相關的命令,並且將檔案上傳到伺服器。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.