Q132284591 发表于 2018-1-3 06:52:17

paramiko模拟ansible远程执行命令

#!/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("请输入是否需要继续输入命令,是按,否按")
  
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()
  
页: [1]
查看完整版本: paramiko模拟ansible远程执行命令