写一个代码同时控制多台远程主机,执行相同的命令。
import paramiko
import threading
# SSH connection details
hostnames = ["192.168.0.101"
# ,"192.168.0.102"
, "192.168.0.103"
, "192.168.0.104"
,"192.168.0.105"
]
username = 'wheeltec'
password = 'dongguan'
command = '/home/wheeltec/wheeltec_robot/src/wheeltec_multi/scripts/centralized_tan.sh' # Command to execute on remote machines
cmd = 'DISPLAY=:0 bash /home/wheeltec/wheeltec_robot/src/wheeltec_multi/scripts/killall.sh'
clients={}
# Create an SSH client
for ip in hostnames:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# client.connect(ip, username=username, password=password)
clients[ip]=client
# Maintain a list of active threads
threads = []
# Connect to the remote machines and execute the command
def ssh_command(hostname,client):
try:
# Connect to the remote machine
client.connect(hostname, username=username, password=password)
# Execute the command
print('\n\n****\n\n',hostname)
stdin, stdout, stderr = clients[hostname].exec_command(command)
# Print the output
print(f'Output from {hostname}:')
print(stdout.read().decode())
except paramiko.AuthenticationException:
print(f'Authentication failed for {hostname}')
except paramiko.SSHException as ssh_ex:
print(f'Unable to establish SSH connection to {hostname}: {ssh_ex}')
finally:
# Close the SSH connection
client.close()
def ssh_cmd(hostname,cmd):
# Execute the command
try:
print('\n\n*ssh cmd***\n\n',hostname)
stdin, stdout, stderr = clients[hostname].exec_command(cmd)
# Print the output
print(f'ssh cmd Output from {hostname}:')
print(stdout.read().decode())
except AttributeError as e:
print(e)
# Function to handle user input
def handle_input():
while True:
choice = input('Enter 0 to exit: 1kill nodes;2 launch nodes')
if choice == '0':
# Close all SSH connections
for k in clients.keys():
clients[k].close()
# Wait for all threads to complete
for thread in threads:
thread.join()
break
if choice == '1':#
# Close all SSH connections
for k in clients.keys():
ssh_cmd(k,cmd)
if choice == '2':#
# Close all SSH connections
for k in clients.keys():
ssh_cmd(k,command)
# Start a separate thread to handle user input
input_thread = threading.Thread(target=handle_input)
input_thread.start()
# Create threads for each remote machine and start them
for hostname in hostnames:
thread = threading.Thread(target=ssh_command, args=(hostname,clients[hostname]))
thread.start()
threads.append(thread)
# Wait for all threads to complete
for thread in threads:
thread.join()
# Wait for the input thread to complete
input_thread.join()