下面是一个封装了连接多个Linux服务器的示例类,可通过三方库paramiko在自己windows机器本机操作linux系统的机器,执行相对应的命令
import paramiko
class MultiLinuxConnection:
def __init__(self):
self.connections = []
def add_connection(self, host, port, username, password):
"""
添加Linux服务器连接。
"""
connection = paramiko.SSHClient() # 实例化SSHClient
connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自动添加策略,保存服务器的主机名和密钥信息,如果不添加,那么不再本地know_hosts文件中记录的主机将无法连接
connection.connect(host, port=port, username=username, password=password) # 连接SSH服务端,以用户名和密码进行认证
self.connections.append(connection)
def remove_connection(self, index):
"""
移除指定索引处的Linux服务器连接。
"""
if index < len(self.connections):
connection = self.connections.pop(index)
connection.close()
def execute_command(self, index, command):
"""
在指定索引处的Linux服务器上执行命令并返回输出结果。
"""
if index < len(self.connections):
connection = self.connections[index]
stdin, stdout, stderr = connection.exec_command(command) #执行命令
output = stdout.read().decode().strip()
return output
def execute_command_all(self, command):
"""
在所有连接的Linux服务器上执行命令并返回输出结果的字典。
"""
output_dict = {}
for index, connection in enumerate(self.connections):
output_dict[index] = self.execute_command(index, command)
return output_dict
def close_all_connections(self):
"""
关闭所有连接的Linux服务器。
"""
for connection in self.connections:
connection.close()
self.connections = []
if __name__ == '__main__':
pass
multi_linuxs = MultiLinuxConnection()
multi_linuxs.add_connection("hostname1", 22, "username1", "password1") #索引0 机器
multi_linuxs.add_connection("hostname2", 22, "username2", "password2") #索引为1 机器
output = multi_linuxs.execute_command(0, "df -h") 索引从0开始
print(output) # 执行索引为0的连接上的命令并打印输出结果
output_all = multi_linuxs.execute_command_all("ifconfig")
print(output_all) # 执行所有连接上的config命令,并打印输出结果的字典
multi_linuxs.remove_connection(1) # 移除索引为1的连接
multi_linuxs.close_all_connections() # 关闭所有连接的SSH连接
这个示例中的MultiLinuxConnection类有以下几个方法:
add_connection: 添加Linux服务器连接,在给定的主机、用户名和密码下建立SSH连接。
remove_connection: 移除指定索引处的Linux服务器连接,并关闭该SSH连接。
execute_command: 在指定索引处的Linux服务器上执行命令,并返回输出结果。
execute_command_all: 在所有连接的Linux服务器上执行命令,并返回包含输出结果的字典。
close_all_connections: 关闭所有连接的Linux服务器的SSH连接。