paramiko是python的SSH庫,可用來連接遠程linux主機,然后執行linux命令或者通過SFTP傳輸文件。
關于使用paramiko執行遠程主機命令可以找到很多參考資料了,本文在此基礎上做一些封裝,便于擴展與編寫腳本。
下面直接給出代碼:
# coding: utf-8import paramikoimport refrom time import sleep# 定義一個類,表示一臺遠端linux主機class Linux(object): # 通過IP, 用戶名,密碼,超時時間初始化一個遠程Linux主機 def __init__(self, ip, username, password, timeout=30): self.ip = ip self.username = username self.password = password self.timeout = timeout # transport和chanel self.t = '' self.chan = '' # 鏈接失敗的重試次數 self.try_times = 3 # 調用該方法連接遠程主機 def connect(self): while True: # 連接過程中可能會拋出異常,比如網絡不通、鏈接超時 try: self.t = paramiko.Transport(sock=(self.ip, 22)) self.t.connect(username=self.username, password=self.password) self.chan = self.t.open_session() self.chan.settimeout(self.timeout) self.chan.get_pty() self.chan.invoke_shell() # 如果沒有拋出異常說明連接成功,直接返回 print u'連接%s成功' % self.ip # 接收到的網絡數據解碼為str print self.chan.recv(65535).decode('utf-8') return # 這里不對可能的異常如socket.error, socket.timeout細化,直接一網打盡 except Exception, e1: if self.try_times != 0: print u'連接%s失敗,進行重試' %self.ip self.try_times -= 1 else: print u'重試3次失敗,結束程序' exit(1) # 斷開連接 def close(self): self.chan.close() self.t.close() # 發送要執行的命令 def send(self, cmd): cmd += '/r' # 通過命令執行提示符來判斷命令是否執行完成 p = re.compile(r':~ #') result = '' # 發送要執行的命令 self.chan.send(cmd) # 回顯很長的命令可能執行較久,通過循環分批次取回回顯 while True: sleep(0.5) ret = self.chan.recv(65535) ret = ret.decode('utf-8') result += ret if p.search(ret): print result return result
下面進行測試:
# 主機IP錯誤,無法連接的情況if __name__ == '__main__': host = Linux('192.168.180.12', 'root', 'xxxx') host.connect() 6 host.send('ls -l') host.close()按 Ctrl+C 復制代碼按 Ctrl+C 復制代碼連接192.168.180.12失敗,進行重試連接192.168.180.12失敗,進行重試連接192.168.180.12失敗,進行重試重試3次失敗,結束程序Process finished with exit code 1
# 鏈接正常的情況if __name__ == '__main__': host = Linux('192.168.180.128', 'root', 'love') host.connect() host.send('ls -l') host.close()運行結果:連接192.168.180.128成功Last login: Sat May 21 07:25:39 2016 from 192.168.180.1Have a lot of fun...ls -l192:~ # ls -ltotal 28-rw------- 1 root root 18 May 21 07:17 .bash_historydrwxr-xr-x 1 root root 28 May 21 06:02 .configdrwx------ 1 root root 22 May 21 05:57 .dbusdrwx------ 1 root root 0 Sep 25 2014 .gnupgdrwxr-xr-x 1 root root 10 May 21 06:15 .local-rw------- 1 root root 55 May 21 06:03 .xauth5mesuo-rw------- 1 root root 55 May 21 07:22 .xauthEYqDmK-rw------- 1 root root 55 May 21 07:25 .xauthGTrohO-rw------- 1 root root 55 May 21 07:09 .xauthP90TnG-rw------- 1 root root 48 May 21 07:40 .xauthjW8pI9-rw------- 1 root root 48 May 21 07:40 .xauthx8T4EDdrwxr-xr-x 1 root root 0 Sep 25 2014 bindrwxr-xr-x 1 root root 38 May 21 05:43 inst-sys192:~ # Process finished with exit code 0
新聞熱點
疑難解答