Python3 telnet_base64_data_analysis_test(借鉴补充)

telnetClient.py

import logging
import telnetlib
import time

class TelnetClient():
def __init__(self,):
self.tn = telnetlib.Telnet()
# 此函数实现telnet登录主机
def login_host(self,host_ip,username,password):
try:
# self.tn = telnetlib.Telnet(host_ip,port=23)
print('start connect...')
self.tn.open(host_ip,port=23)
print('con... end')
except:
logging.warning('%s网络连接失败'%host_ip)
return False
# 等待login出现后输入用户名,最多等待10
self.tn.read_until(b'login: ',timeout=10)
self.tn.write(username.encode('utf-8') + b'\n')
# 等待Password出现后输入用户名,最多等待10
self.tn.read_until(b'Password: ',timeout=10)
self.tn.write(password.encode('utf-8') + b'\n')
# 延时两秒再收取返回结果,给服务端足够响应时间
time.sleep(2)
# 获取登录结果
# read_very_eager()获取到的是的是上次获取之后本次获取之前的所有输出
command_result = self.tn.read_very_eager().decode('utf-8')
if 'Login incorrect' not in command_result:
logging.warning('%s登录成功'%host_ip)
return True
else:
logging.warning('%s登录失败,用户名或密码错误'%host_ip)
return False

# 此函数实现执行传过来的命令,并输出其执行结果
def execute_some_command(self,command):
# 执行命令
self.tn.write(command.encode('utf-8')+b'\n')
time.sleep(2)
# 获取命令结果
command_result = self.tn.read_very_eager().decode('utf-8')
logging.warning('命令执行结果:\n%s' % command_result)
return command_result

# 退出telnet
def logout_host(self):
self.tn.write(b"exit\n")


if __name__ == '__main__':
print('333')
host_ip = '192.168.1.46'
username = 'root'
password = '123456'
command = 'cd /home/test && cat file1 |grep sshd'
telnet_client = TelnetClient()
# 如果登录结果返加True,则执行命令,然后退出
if telnet_client.login_host(host_ip,username,password):
telnet_client.execute_some_command(command)
telnet_client.logout_host()


test.py

from telnetClient import TelnetClient
import base64

host_ip = '192.168.1.46'
username = 'root'
password = '123456'
command = 'cd /home/test && cat file2'
telnet_client = TelnetClient()
# 如果登录结果返加True,则执行命令,然后退出
if telnet_client.login_host(host_ip, username, password):
date1 = telnet_client.execute_some_command(command)
date2 = date1.replace('"', '').split("{")[1].split('}')[0]
list1 = date2.split(',')
disc1 = {}
for i in range(len(list1)):
list2 = list1[i].split(':')
key = list2[0]
value = list2[1]
disc1[key] = value
es = disc1['Event_Data']
print(es)
ds = base64.b64decode(es.encode('utf-8')).decode('utf-8')
print(ds)
telnet_client.logout_host()


telnetClient.py和test.py文件放在同一个目录
 
posted @ 2019-11-19 22:41  fangpinz  阅读(274)  评论(0编辑  收藏  举报