主模块
#!/usr/bin/env python
from multiprocessing import Process
import paramiko
import time
import sys
import new_latest_configparser #导入配置信息模块
# import groupshow
Username = "root"
Password = "123456"
Port = 22
Current_time = time.strftime("%Y-%m-%d %X", time.localtime())
#执行命令处
def runCmd(ip,cmd):
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
s.connect(hostname=ip,port=Port,username=Username,password=Password)
stdin,stdout,stderr = s.exec_command(cmd)
result = stdout.read()
# print(result)
s.close()
print("IP:[%s]at:[%s] run command [%s]".center(50, "-") % (ip, Current_time,cmd))
print(str(result, encoding="utf-8")) except:
print("%s is not exits" %ip)
# if_continue = input("请输入是否需要继续输入命令,是按[Y],否按[N]")
def handle_Process():
while True:
print("欢迎来到ansible模拟系统,主机分组如下".center(50, "-"))
#调用主机信息模块方法
new_latest_configparser.showgroups()
User_choice = str(input("请选择组:").strip())
if len(User_choice) == 0 or User_choice not in new_latest_configparser.GROUP or User_choice.isdigit():
print("请输入正确的组名")
continue
elif User_choice == "webserver":
#打印主机信息处
print(new_latest_configparser.config.get("webserver", "IP"))
print(new_latest_configparser.config.get("webserver", "IP2"))
break elif User_choice == "dbserver":
# print(functions.config.get("dbserver"))
print(new_latest_configparser.config.get("dbserver","IP"))
break
try: cmd = input("please input your cmd:")
#判断主机组
if User_choice == "webserver":
#循环获取IP
for ip in new_latest_configparser.IPlist:
p = Process(target=runCmd,args=(ip,cmd))
p.start() elif User_choice == "dbserver":
for ip in new_latest_configparser.Other_list:
p = Process(target=runCmd, args=(ip, cmd))
p.start()
except IndexError:
print("please input a command")
if __name__ == '__main__':
handle_Process()
配置信息模块
import configparser
config = configparser.ConfigParser()
config.read("host.conf")
sec = config.sections()
kvs = config.items("webserver")
GROUP = [
"webserver",
"dbserver" ]
IP = str(kvs[0][1])
IP2 = str(kvs[1][1])
IPlist = []
IPlist.append(IP)
IPlist.append(IP2) #另外一组信息
Other_kvs = config.items("dbserver")
New_IP = str(Other_kvs[0][1])
Other_list = []
Other_list.append(New_IP)
def showgroups():
for group in sec:
print(group)
配置信息
[webserver]
IP = 192.168.170.143
IP2 = 192.168.170.150
[dbserver]
IP = 192.168.170.129
运行结果