聲明:忘記參考了哪位大神的代碼了,找不到鏈接,如果有發現盜版的請提示我,到時候我把出處添加上。
首先我用的開發環境是window+eclipse,環境的安裝要求:
1、eclipse安裝有python的開發插件
2、window安裝有python
3、pip install paramiko
下面直接上代碼
#!/usr/bin/env python
# encoding: utf-8
'''
Created on 2018年5月10日
@author: Jenson
'''
import paramiko
import time
class ParammikoUtil(object):
# 通過IP, 用戶名,密碼,超時時間初始化一個遠程Linux主機
def __init__(self, ip, username, password, timeout=40):
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
self.receLog()
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()
#獲取log
def receLog (self):
while True :
#每0.5s執行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#print result.split('\n')[len(result.split('\n'))-1]
if result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
#發送一般命令
def runCMD(self , cmd):
cmd += '\r'
# 發送要執行的命令
print '輸入命令:'
self.chan.send(cmd)
#獲取結果
self.receLog()
#輸入安裝軟件的命令
def runInstall(self,cmd):
cmd += '\r'
# 發送要執行的命令
print '輸入命令:'
self.chan.send(cmd)
while True :
#每0.5s執行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#需要輸入y
if result.split('\n')[len(result.split('\n'))-1] == r'Is this ok [y/d/N]: ':
#print 1111
#print result
self.chan.send('y'+'\n')
#判斷是否處理完
elif result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
#發送卸載軟件的命令
def runRemove(self,cmd):
cmd += '\r'
# 發送要執行的命令
print '輸入命令:'
self.chan.send(cmd)
while True :
#每0.5s執行一次
time.sleep(0.5)
result = self.chan.recv(65535).decode('utf-8')
print result
#需要輸入y
if result.split('\n')[len(result.split('\n'))-1] == r'Is this ok [y/N]: ':
#print 1111
#print result
self.chan.send('y'+'\n')
#判斷是否處理完
elif result.split('\n')[len(result.split('\n'))-1] == '[root@master03 ~]# ' :
break
if __name__ == '__main__':
host = ParammikoUtil('master03', 'root', 'root')
host.connect()
#host.runCMD('ls -a')
#host.runInstall('yum install git')
#host.runRemove('yum remove git')
host.close()