import re
import os
import paramiko
import redis
import time
tday_time=time.strftime("%Y-%m-%d", time.localtime()) # 獲取當天的日期時間
file_path = '/Users/macbook/Desktop/log.txt' # 存放Log日志的路徑
class ssh_Liunx():
'''連接服務器'''
def __init__(self,hostname,username,password): # 構造初始化數據
self.hostname = hostname
self.username = username
self.password = password
self.ssh =paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 用ssh連接遠程主機時,第一次連接時會提示是否繼續進行遠程連接,選擇yes
self.ssh.connect(self.hostname,22,self.username,self.password) #連接遠程主機,SSH端口號為22
def ssh_comond(self,commonds): # 執行命令的方法
'''執行命令'''
stdin, stdout, stderr = self.ssh.exec_command(commonds) # 執行命令
result=stdout.readlines()
for line in result:
print(line)
return result
def get_hostname(self): # 獲取服務器主機名
commonds='hostname'
get_hostname=self.ssh_comond(commonds)
return get_hostname
def get_disk_space(self): # 獲取剩余磁盤空間
commonds='df -h'
get_diskspace=self.ssh_comond(commonds)
return get_diskspace
def Transcode(self):# 獲取日志文件信息 輸入到當前目錄下
count=0 # 計數
commonds='cd /xxxx/logs;cat laravel-'+tday_time+'.log' # linux執行命令
get_transcode=self.ssh_comond(commonds) # 調用方法具體執行
for line in get_transcode: # 讀取當前獲取的日志信息
with open(file_path,'a+') as fp: # 本地生產log文件
fp.write(line) # 將日志另到文件中
count+=1
#print("當前文件總計:%s行日志信息"%count)
# print(os.path.getsize(file_path)) # 文件大小 字節
return get_transcode
def re_error(self): # 正則匹配日志的錯誤信息,存在問題,沒有匹配出來,待繼續處理
matches=[]
identifier_pattern = re.compile(r'Identifier: (.*?)$')
with open(file_path, 'a+') as fp:
for line in fp:
matches+=re.findall(identifier_pattern,line)
print("matches", matches)
def closed(self): # 關閉連接
self.ssh.close()
if name == 'main':
hostname = '127.0.0.1'
username = 'username'
password = 'password
ssh = ssh_test(hostname, username, password)
print(ssh.Transcode())
不完善之處還請多多指教