# -*- coding:utf-8 -*-
# author: cyz
# time: 2021/8/20 15:04
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
# os.chdir(os.path.dirname(os.path.abspath(__file__)))
from datetime import datetime
import telnetlib
import time
import re
from internal.pkg.login.kafka_login import ConnectKafka as engine_kafka
class TelnetClient(object):
# https://docs.python.org/3/library/telnetlib.html
"""连接Telnet,调取服务"""
def __init__(self, server_host, server_port):
self.tn = telnetlib.Telnet()
self.server_host = server_host
self.server_port = server_port
# telnet登录主机
def connect(self):
try:
# print(f"telent connect to {self.server_host}:{self.server_port}")
self.tn.open(self.server_host, port=self.server_port)
return True
except Exception as e:
print(str(e))
return False
def execute(self, command:str,block:int = 1, **kwargs):
'''
执行telnet命令
:param command:telnet命令,eg:ls 列出所有可用的服务; ls 服务名 ,列出服务下所有的方法;ls -l 服务名 ,列出服务下的所有方法和参数
:param block:是否阻塞,默认不阻塞,若为0则阻塞
:param listen_match:阻塞下监听的字符
:param tims_limit:阻塞下监听的时长,若为none则无限时监听
:return:
'''
listen_match = kwargs.get("listen_match", None)
tims_limit = kwargs.get("tims_limit", 10)
self.tn.write(command.encode('utf-8') + b"\n")
if block:
result = self.tn.read_very_eager().decode(encoding='utf-8').split('\r\n')[0]
else:
result = self.tn.read_until(listen_match.encode('utf-8'), tims_limit).decode(encoding='utf-8').split('\r\n')[0]
if result == "":
print("没有返回监听的数据结果")
return result
def close(self):
self.tn.write(b"exit\n")
# print("close telnet connect")
def __call__(self, command, block, **kwargs):
while 1:
if self.connect():
break
else:
time.sleep(10)
result = self.execute(command, block, **kwargs)
self.close()
return result
class DubboError(Exception):
pass
class UnknownParameterClassForNameError(DubboError): # 发送字符导致服务判断错误
pass
class NoResponseError(DubboError): # 没有返回信息错误
pass
class DubboLoginError(DubboError): # 登陆错误
pass
class ConnectDubbo():
def __init__(self):
self.dubbo_host = '1.1.1.1'
self.dubbo_port = "20880"
self.kafka_topic = "spider.topic" #
self.key = b'spiderResult' # 键
self.telnet_client = TelnetClient(self.dubbo_host, self.dubbo_port)
self.login_flag = self.telnet_client.connect()
if self.login_flag == False:
raise DubboLoginError("login error")
def execute(self,data):
cmd ="invoke " + data.get("dubbo_service") + "." + data.get("dubbo_method") + str(data.get("parameters"))
# print("调用命令是:{}".format(cmd))
result = ""
try:
result = self.telnet_client.execute(cmd, block=0, listen_match="dubbo>", time_limit=10)
resp_code = re.findall('\{"code":(.*?),.*?\}', result)
if resp_code != ["200"]:
if result == "":
raise NoResponseError("Can not catch response (listen time out)")
elif re.findall('Unknown parameter class for name', result) == []:
raise DubboError(result)
else:
raise UnknownParameterClassForNameError(result)
else:
print(f'{datetime.now().strftime("%B Week %w %A: [%Y-%m-%d %H:%M:%S %f]")}, dubbo send msg result ->',
result.replace("}",f',"json_str":{self.json_str}}}'))
except UnknownParameterClassForNameError as upcfne:
print(upcfne)
ck = engine_kafka()
ck.send(self.client_id, self.kafka_topic, self.json_str, key=self.key)
except NoResponseError as nre:
print(nre)
ck = engine_kafka()
ck.send(self.client_id, self.kafka_topic, self.json_str, key=self.key)
except Exception as e:
# raise DubboError("调用接口异常, 接口响应是result={}, 异常信息为:{}".format(result, e))
print(f"调用接口异常, 接口响应是result={result}, 异常信息为:{e}")
ck = engine_kafka()
ck.send(self.client_id, self.kafka_topic, self.json_str, key=self.key)
self.logout()
def logout(self):
self.telnet_client.close()
def __call__(self,spider_id,json_str:str):
self.client_id = spider_id
self.json_str = json_str
data = {
'dubbo_service': 'com.datatx.core.dubbo.AdminService',
'dubbo_method': 'sendNextNodeByNodeId',
'parameters': (f"<StartInfo>{spider_id}</StartInfo><Info>{json_str}</Info>",)
}
self.execute(data)
if __name__ == '__main__':
a = "a"
cd = ConnectDubbo()
cd(1,a)
dubbo
最新推荐文章于 2024-06-23 14:14:18 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)