#應用 連接timesten 數據庫
host = Linux(ip, 'user', 'pwd') # 傳入Ip,用戶名,密碼
host.connect() #主機開啟
cdsql = host.send('ttisql smscc') # 發送一個查看ip的命令
selInfo = host.send('select count(0) from smscc.mtinfo;') #發送命令
host.close() #主機關閉
# 定義一個類,表示一台遠端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 as 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('root@scdel-02:.*?#')
result = ''
# 發送要執行的命令
self.chan.send(cmd)
# 回顯很長的命令可能執行較久,通過循環分批次取回回顯,執行成功返回true,失敗返回false
while True:
time.sleep(0.5)
ret = self.chan.recv(65535)
ret = ret.decode('utf-8')
result += ret
return result