使用python语言基于面向对象思想利用paramiko远程进服务器,批量ping并声音报警
时间: 2024-05-14 15:17:00 浏览: 24
好的,我明白了您的要求和问题。可以使用Python中的paramiko模块连接到远程服务器,并使用os模块执行ping命令。
下面是一个示例代码,可以根据您的具体需求进行修改:
```python
import os
import paramiko
import time
import winsound
class Server:
def __init__(self, ip, username, password):
self.ip = ip
self.username = username
self.password = password
def connect(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(self.ip, username=self.username, password=self.password)
return ssh
def ping(self, ip):
response = os.system("ping -n 1 " + ip)
if response == 0:
print(ip, 'is up!')
return True
else:
print(ip, 'is down!')
return False
def ping_servers(self, server_ips):
while True:
for ip in server_ips:
if not self.ping(ip):
# play sound when server is down
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
time.sleep(10) # delay 10 seconds before running ping again
if __name__ == '__main__':
# server settings
server_ip = 'your_server_ip'
server_username = 'your_username'
server_password = 'your_password'
server_ips = ['server_ip_1', 'server_ip_2', 'server_ip_3']
# connect to server
server = Server(server_ip, server_username, server_password)
ssh = server.connect()
# run ping and sound alert
server.ping_servers(server_ips)
# close connection
ssh.close()
```
需要注意的是,在运行Ping命令时,需要根据不同的操作系统进行修改。上述代码是在Windows系统下运行的ping命令。如果在Linux系统下运行,需要修改为`ping -c 1`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)