给我写一个多线程操作服务器执行命令的Python脚本
时间: 2023-05-27 07:04:50 浏览: 92
python 多线程脚本
下面是一个多线程操作服务器执行命令的Python脚本,使用了paramiko模块:
```python
import threading
import paramiko
class ServerThread(threading.Thread):
def __init__(self, host, user, password, command):
threading.Thread.__init__(self)
self.host = host
self.user = user
self.password = password
self.command = command
def run(self):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(self.host, username=self.user, password=self.password, timeout=5)
print(f"Connected to {self.host}")
stdin, stdout, stderr = ssh.exec_command(self.command)
output = stdout.read().decode('utf-8')
print(output)
except Exception as e:
print(f"Failed to connect to {self.host}: {e}")
finally:
ssh.close()
if __name__ == '__main__':
hosts = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
user = 'username'
password = 'password'
command = 'ls -l /'
threads = []
for host in hosts:
thread = ServerThread(host, user, password, command)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print("All commands executed.")
```
该脚本会创建一个ServerThread类,实现了多线程操作多个服务器执行相同的命令。在主程序中,我们定义了需要操作的服务器列表、用户名、密码和命令,然后依次创建每个服务器的线程,启动线程并等待线程执行完毕。
阅读全文