python利用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行命令的方法
python中的paramiko模塊是用來實(shí)現(xiàn)ssh連接到遠(yuǎn)程服務(wù)器上的庫,在進(jìn)行連接的時候,可以用來執(zhí)行命令,也可以用來上傳文件。
1、得到一個連接的對象
在進(jìn)行連接的時候,可以使用如下的代碼:
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函數(shù)中,參數(shù)是一個主機(jī)的IP地址或者是主機(jī)名稱,在執(zhí)行這個方法之后,如果成功的連接到服務(wù)器,那么就會返回一個sshclient對象。
第一步是建立一個SSHClient的對象,然后設(shè)置ssh客戶端允許連接不在know_host文件中的機(jī)器,然后就嘗試連接服務(wù)器,在連接服務(wù)器的時候,可以使用兩種方式:一種方式是使用秘鑰的方式,也就是參數(shù)look_for_keys,這里用設(shè)置密碼尋找,也可以直接使用密碼的方式,也就是直接使用參數(shù)password,從而最后返回一個連接的對象。
2、 獲取設(shè)置的命令
在進(jìn)行paramiko連接之后,那么必須要得到需要執(zhí)行的命令,如下代碼所示:
def command(args,outpath): 'this is get the command the args to return the command' cmd = '%s %s' % (outpath,args) return cmd
在參數(shù)中,一個是args,一個outpath,args表示命令的參數(shù),而outpath表示為可執(zhí)行文件的路徑,例如/usr/bin/ls -l。在其中outpath也就是/usr/bin/ls ,而參數(shù)為-l
這個方法主要是用來組合命令,將分開的參數(shù)作為命令的一部分進(jìn)行組裝。
3、 執(zhí)行命令
在連接過后,可以進(jìn)行直接執(zhí)行命令,那么就有了如下的函數(shù):
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
在此函數(shù)中,傳入的參數(shù)一個為連接的對象conn,一個為需要執(zhí)行的命令cmd,最后得到執(zhí)行的結(jié)果,也就是stdout.read(),最后返回得到的結(jié)果
4、 上傳文件
在使用連接對象的時候,也可以直接進(jìn)行上傳相關(guān)的文件,如下函數(shù):
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
此函數(shù)的主要參數(shù)為,一個是連接對象conn,一個是上傳的文件名稱,一個上傳之后的文件名稱,在此必須寫入完整的文件名稱包括路徑。
做法主要是打開一個sftp對象,然后使用put方法進(jìn)行上傳文件,最后關(guān)閉sftp連接,最后返回一個上傳的文件名稱的完整路徑
5、 執(zhí)行命令得到結(jié)果
最后就是,執(zhí)行命令,得到返回的結(jié)果,如下代碼:
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]
首先,進(jìn)行連接服務(wù)器,得到一個連接對象,如果連接不成功,那么返回主機(jī)名和None,表示沒有連接成功,如果連接成功,那么修改文件的執(zhí)行權(quán)限,從而可以執(zhí)行文件,然后得到執(zhí)行的命令,最后,進(jìn)行執(zhí)行命令,得到結(jié)果,將結(jié)果用json格式表示返回,從而結(jié)果能得到一個美觀的json格式,最后和主機(jī)名一起返回相關(guān)的信息
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')
第一步測試命令執(zhí)行,第二步測試上傳文件,第三部測試修改上傳文件的權(quán)限。
完整代碼如下:
#!/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服務(wù)器,然后執(zhí)行相關(guān)的命令,并且將文件上傳到服務(wù)器。
以上這篇python利用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行命令的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何解決cmd運(yùn)行python提示不是內(nèi)部命令
在本篇文章里小編給大家整理了關(guān)于如何解決cmd運(yùn)行python提示不是內(nèi)部命令的相關(guān)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2020-07-07深入淺析python中的多進(jìn)程、多線程、協(xié)程
這篇文章主要介紹了深入淺析python中的多進(jìn)程、多線程、協(xié)程 的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-06-06python中for循環(huán)的多種使用實(shí)例
for語句是Python中執(zhí)行迭代的兩個語句之一,另一個語句是while,下面這篇文章主要給大家介紹了關(guān)于python中for循環(huán)的多種使用方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09Python 機(jī)器學(xué)習(xí)之線性回歸詳解分析
回歸是監(jiān)督學(xué)習(xí)的一個重要問題,回歸用于預(yù)測輸入變量和輸出變量之間的關(guān)系,特別是當(dāng)輸入變量的值發(fā)生變化時,輸出變量的值也隨之發(fā)生變化。回歸模型正是表示從輸入變量到輸出變量之間映射的函數(shù)2021-11-11Python壓縮包處理模塊zipfile和py7zr操作代碼
目前對文件的壓縮和解壓縮比較常用的格式就是zip格式和7z格式,這篇文章主要介紹了Python壓縮包處理模塊zipfile和py7zr,需要的朋友可以參考下2022-06-06使用Pytest.main()運(yùn)行時參數(shù)不生效問題解決
本文主要介紹了使用Pytest.main()運(yùn)行時參數(shù)不生效問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Python通過dxfgrabber庫實(shí)現(xiàn)獲取CAD信息
dxfgrabber?是一個?Python?庫,用于讀取和解析?AutoCAD?DXF(Drawing?Exchange?Format)文件,本文就來教教大家如何利用dxfgrabber庫實(shí)現(xiàn)獲取CAD信息吧2023-06-06Keras框架中的epoch、bacth、batch size、iteration使用介紹
這篇文章主要介紹了Keras框架中的epoch、bacth、batch size、iteration使用介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06