paramiko
```
from colorama import init, Fore
import paramiko
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
init(autoreset=True)
local = """
192.168.111.66 rootroot
192.168.111.128 rootroot
""".strip().split("\n")
easyviews = """
10.1.125.23 ROOTROOT
10.1.125.24 rootroot
10.1.125.32 rootroot
10.1.125.37 rootroot
10.1.125.43 3BTWEfxv#%
10.1.125.45 3BTWEfxv#%
10.1.125.46 #1AjvLUxPj
10.1.125.47 #1AjvLUxPj
10.1.125.48 X@@vwWX@M8
10.1.125.49 rootroot
10.1.125.60 rootroot
10.1.125.162 rootroot
10.1.125.164 rootroot
10.1.125.200 Greattimes601
""".strip().split("\n")
class SSHClient:
def __init__(self, host, username, password, port=22):
self.host = host
self.username = username
self.password = password
self.port = port
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh_client.connect(self.host, self.port, self.username, self.password)
self.ssh_client = ssh_client
except Exception as e:
print(f"[{datetime.now().strftime('%m-%d %H:%M:%S')}] [ERROR] [{host}]连接失败:{e}") # %Y-%m-%d %H:%M:%S
def color_message(self,ip, cmd):
msg_head = f"[{ip}] exec => [{cmd}] {'-' * 35}> \n"
return msg_head
def exec(self, cmd: str):
stdin, stdout, stderr = self.ssh_client.exec_command(cmd)
result = {
'stderr': stderr.read().decode('utf-8'),
'stdout': stdout.read().decode('utf-8')
}
successed = f'{Fore.GREEN + self.color_message(ip, cmd) + Fore.RESET} {result["stdout"]} {Fore.GREEN + "-" * 50 + Fore.RESET}\n'
failed = f'{Fore.RED + self.color_message(ip, cmd) + Fore.RESET} {result["stderr"]} {Fore.RED + "-" * 50 + Fore.RESET}\n'
if result['stderr'] == "":
print(successed)
elif result['stdout'] == "":
print(failed)
else:
print(successed,failed)
return result
def __del__(self):
self.ssh_client.close()
def sshExecCMD(ip, username, password, cmd, port):
ssh = SSHClient(ip, username, password, port)
ssh.exec(cmd)
group = local
cmds = """
hostnamectl
ls
""".strip().split("\n")
pool = ThreadPoolExecutor(5)
for cmd in cmds:
for ip_info in group:
ip = ip_info.split()
if len(ip) >= 2:
pool.submit(sshExecCMD, ip[0], "root", ip[1], cmd, 22)
# sshExecCMD(ip[0], "root", ip[1], cmd, 22)
```
`settings.py`
```python
'''当所有账户密码都相同时只写第一个IP的user和passwd即可,空格隔开,空user,passwd默认取第一行IP的user和passwd'''
hostname_str = """
10.1.125.39 root rootroot
101.43.129.109 root Zgy666..
192.168.59.128
10.1.125.40
10.1.125.41
10.1.125.42
10.1.125.43
10.1.125.60
10.1.125.162
"""
#要执行的命令
context = """
cd /mnt
pwd
free -h
date
"""
host_infos = hostname_str.strip().split("\n")
```
`cmd.py`
```python
# coding:utf-8
import paramiko
from concurrent.futures import ThreadPoolExecutor
from settings import *
def ret_res(cmd,result):
print("执行命令:",cmd,"\n返回结果:",result)
def cmd_client(hostname, cmd, username, password, port=22):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(cmd,timeout=5)
result = [stdout.read().decode('utf-8'), stderr.read().decode("utf-8")]
if result[1]:
if result[0]:
print(hostname,"连接成功 ======>")
ret_res(cmd,result[0])
print(hostname, "命令执行出错 =====>:")
ret_res(cmd, result[1])
else:
print(hostname, "连接成功 ======>")
ret_res(cmd, result[0])
ssh.close()
except Exception as e:
print("%s 连接失败======>\n " % hostname, e)
def get_host(host_info):
try:
host,user,passwd = host_info.strip().split()
except:
user_passwd = host_infos[0].strip().split()
user,passwd = user_passwd[1],user_passwd[2]
host = host_info
return (host,user,passwd)
def ssh_cmd(cmd):
for host_info in host_infos:
host,user,passwd = get_host(host_info.strip())
if host[0] != "#":
cmd_client(host, cmd, user, passwd)
def Thread_cmd(cmd):
pool = ThreadPoolExecutor(10)
for host_info in host_infos:
host, user, passwd = get_host(host_info.strip())
if host[0] != "#":
pool.submit(cmd_client,host,cmd,user,passwd)
context = context.strip().split('\n')
if __name__ == '__main__':
for cmd in context:
# Thread_cmd(cmd)
ssh_cmd(cmd)
```
`cmdclient.py`
```python
# coding:utf-8
import paramiko
from concurrent.futures import ThreadPoolExecutor
from settings import *
def cmd_client(hostname, cmd, username, password, port=22):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(cmd,timeout=5)
result = [stdout.read().decode('utf-8'), stderr.read().decode("utf-8")]
if result[1]:
if result[0]:
print(hostname, "success ======>\n", result[0])
print(hostname, "command err =====>\n:", result[1])
else:
print(hostname, "success ======>\n", result[0])
ssh.close()
except Exception as e:
print("%s filed======>\n " % hostname, e)
def get_host(host_info):
try:
host,user,passwd = host_info.strip().split()
except:
user_passwd = host_infos[0].strip().split()
user,passwd = user_passwd[1],user_passwd[2]
host = host_info
return (host,user,passwd)
def ssh_cmd(cmd):
for host_info in host_infos:
host,user,passwd = get_host(host_info.strip())
if host[0] != "#":
cmd_client(host, cmd, user, passwd)
def Thread_cmd(cmd):
pool = ThreadPoolExecutor(10)
for host_info in host_infos:
host, user, passwd = get_host(host_info.strip())
if host[0] != "#":
pool.submit(cmd_client,host,cmd,user,passwd)
if __name__ == '__main__':
# ssh_cmd(context)
Thread_cmd(context)
```