paramiko 3-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
import paramiko
import concurrent.futures
def execute_remote_command(hostname, username, password, command):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command, timeout=10)
print(f"在主机 {hostname} 上执行命令: {command}")
print("--------")
for line in stdout:
print(line.strip())
print("--------")
return hostname, True
except paramiko.AuthenticationException:
print(f"无法连接到主机: {hostname}认证失败。")
return hostname, False
except paramiko.ssh_exception.SSHException as e:
if "timed out" in str(e):
print(f"在主机 {hostname} 上执行命令超时。")
else:
print(f"在主机 {hostname} 上执行命令时出现错误: {str(e)}")
return hostname, False
finally:
if client:
client.close()
def read_servers_from_file(file_path):
servers = []
with open(file_path, 'r') as file:
for line in file:
fields = line.strip().split(',')
if len(fields) == 3:
server = {
"hostname": fields[0],
"username": fields[1],
"password": fields[2]
}
servers.append(server)
return servers
command = "ls -l"
servers = read_servers_from_file("servers.txt")
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = {executor.submit(
execute_remote_command,
server["hostname"],
server["username"],
server["password"],
command): server["hostname"] for server in servers}
results = {}
for future in concurrent.futures.as_completed(futures):
hostname = futures[future]
try:
result = future.result()
results[hostname] = result[1]
except Exception as e:
print(f"在主机 {hostname} 上执行命令时出现错误: {str(e)}")
print("\n连接失败或超时的主机:")
for hostname, success in results.items():
if not success:
print(hostname)
servers.txt的文本文件中
172.16.20.108,root,123456
172.16.20.90,root,123qwe
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |