Skip to main content
 首页 » 编程设计

python之如何以编程方式检查 apache tomcat 是否在 python 中运行

2025年02月15日28jirigala

有什么方法可以用 python 从另一台机器检查 apache tomcat 服务器的状态吗?

例如,在8086 端口有apache tomcat 服务器的机器上运行一个restful API。

现在,我想要的是在 python 中以编程方式从我的电脑检查指定机器的 apache tomcat 服务的状态。

是的,我可以通过在 python 中使用 os.system ping 来检查机器是否正在运行。

import os 
hostname = "xxx.xxx.xxx.xxx" #example 
response = os.system("ping -c 1 " + hostname) 
 
#and then check the response... 
if response == 0: 
    print hostname, 'is up!' 
else: 
    print hostname, 'is down!' 

但是,我感兴趣的是,是否可以在 python 中以编程方式检查服务 (real_ip:8086/BotAPI) 的状态而不是机器的活跃度?

更新:使用 paramiko 我得到了以下回溯

channel.exec_command('ps -ef| grep tomcat') 
Traceback (most recent call last): 
File "<pyshell#67>", line 1, in <module> 
channel.exec_command('ps -ef| grep tomcat') 
File "E:\python\lib\site-packages\paramiko\channel.py", line 63, in _check 
return func(self, *args, **kwds) 
File "E:\python\lib\site-packages\paramiko\channel.py", line 241, in exec_command 
self._wait_for_event() 
File "E:\python\lib\site-packages\paramiko\channel.py", line 1197, in _wait_for_event 
raise e 
paramiko.ssh_exception.SSHException: Channel closed. 

请您参考如下方法:

您可以使用 fabric 或 paramiko 远程连接到您的 tomcat 机器,然后检查该进程是否正在运行

import paramiko 
 
ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect('hostname', username='user', password='password') 
 
transport = ssh.get_transport() 
channel = transport.open_session() 
channel.exec_command('ps -ef | grep tomcat') 
 
status = channel.recv_exit_status()