首頁  >  文章  >  後端開發  >  詳解python之簡單主機批次管理工具

詳解python之簡單主機批次管理工具

高洛峰
高洛峰原創
2017-02-04 15:12:411246瀏覽

今天做了一個很簡單的小項目,感受到了paramiko模組的強大,也深感自己Linux的功力不行~~

一、需求

詳解python之簡單主機批次管理工具

二、簡單需求分析及需求很少,我就簡單地說下:

1. 主機分組可以設定檔實作(我用字典存資料的).

2. 登陸功能不做。選擇分組後可查看群組內對應主機的主機名稱和IP位址.

3. >>>cmd: df(輸入指令則起多個執行緒(視群組內有多少主機而定)同時執行)

輸出:

——————————————h1————————————

……(命令返回的資料)

———— —————————h2————————————

……

>>>put  test.yy(本地檔案)   filename (把本地的test.yy檔案傳到遠端主機的/root目錄下)

4.可寫在設定檔中。包含遠端主機的: 主機名稱IP 使用者名稱密碼連接埠

流程圖

三、目錄結構及原始碼詳解python之簡單主機批次管理工具

目錄結構:

.

main.py(批次主機管理介面)

"""批量主机管理接口"""
 
import core
 
if __name__ == "__main__":
  core.run()
詳解python之簡單主機批次管理工具core.py(核心程式碼,被介面呼叫)

"""核心代码"""
import settings
import paramiko
import threading
import os
 
 
class REMOTE_HOST(object):
  #远程操作主机
  def __init__(self, host, port ,username, password, cmd):
    self.host = host
    self.port = port
    self.username = username
    self.password = password
    self.cmd = cmd
 
  def run(self):
    """起线程连接远程主机后调用"""
    cmd_str = self.cmd.split()[0]
    if hasattr(self, cmd_str):   #反射 eg:调用put方法
      getattr(self, cmd_str)()
    else:
      #setattr(x,'y',v)is equivalent to  ``x.y=v''
      setattr(self, cmd_str, self.command)
      getattr(self, cmd_str)() #调用command方法,执行批量命令处理
 
  def command(self):
    """批量命令处理"""
    ssh = paramiko.SSHClient() #创建ssh对象
    #允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=self.host,port=self.port,username=self.username,password=self.password)
    stdin,stdout,stderr = ssh.exec_command(self.cmd)
    result = stdout.read()
    print("%s".center(50, "-") % self.host)
    print(result.decode())
    ssh.close()
 
  def put(self):
    """上传文件"""
    filename = self.cmd.split()[1] #要上传的文件
    transport = paramiko.Transport((self.host, self.port))
    transport.connect(username=self.username, password=self.password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.put(filename, filename)
    print("put sucesss")
 
    transport.close()
 
 
def show_host_list():
  """通过选择分组显示主机名与IP"""
  for index, key in enumerate(settings.msg_dic):
    print(index + 1, key, len(settings.msg_dic[key]))
  while True:
    choose_host_list = input(">>>(eg:group1)").strip()
    host_dic = settings.msg_dic.get(choose_host_list)
    if host_dic:
      #print(host_dic)
      for key in host_dic:
        print(key, host_dic[key]["IP"])
      return host_dic
    else:
      print("NO exit this group!")
 
 
def interactive(choose_host_list):
  """根据选择的分组主机起多个线程进行批量交互"""
  thread_list = []
  while True:
    cmd = input(">>>").strip()
    if cmd:
      for key in choose_host_list:
        host, port, username, password = choose_host_list[key]["IP"], choose_host_list[key]["port"], \
                         choose_host_list[key]["username"], choose_host_list[key]["password"]
        func = REMOTE_HOST(host, port, username, password, cmd) # 实例化类
        t = threading.Thread(target=func.run) # 起线程
        t.start()
        thread_list.append(t)
      for t in thread_list:
        t.join() # 主线程等待子线程执行完毕
    else:
      continue
 
 
def run():
  choose_host_list = show_host_list()
  interactive(choose_host_list)

settings.py(設定檔)

"""配置文件"""
 
msg_dic = {
  "group1":{  #分组1
    "h1":{"IP":"192.168.1.1", "username":"11", "password":"aa", "port":22},
    "h2":{"IP":"192.168.1.2", "username":"22", "password":"bb", "port":22},
    "h3":{"IP":"192.168.1.3", "username":"33", "password":"cc", "port":22},
    "h4":{"IP":"192.168.1.4", "username":"44", "password":"dd", "port":22},
    "h5":{"IP":"192.168.1.5", "username":"55", "password":"ee", "port":22},
    "h6":{"IP":"192.168.1.6", "username":"66", "password":"ff", "port":22},
  },
 
  "group2":{  #分组2
    "h1":{"IP":"192.168.2.1", "username":"111", "password":"aaa", "port":22},
    "h2":{"IP":"192.168.2.2", "username":"222", "password":"bbb", "port":22},
    "h3":{"IP":"192.168.2.3", "username":"333", "password":"ccc", "port":22},
    "h4":{"IP":"192.168.2.4", "username":"444", "password":"ddd", "port":22},
    "h5":{"IP":"192.168.2.5", "username":"555", "password":"eee", "port":22},
    "h6":{"IP":"192.168.2.6", "username":"666", "password":"fff", "port":22},
    "h7":{"IP":"192.168.2.7", "username":"777", "password":"ggg", "port":22},
    "h8":{"IP":"192.168.2.8", "username":"888", "password":"hhh", "port":22},
  },
 
  "group3":{
    "h1":{"IP":"192.168.179.133", "username":"root", "password":"zcl", "port":22},
  }
}

測試:

連接硬體一台虛擬機器測試~

C:\Python34\python3.exe C:/Users/Administrator/PycharmProjects/laonanhai/host_manage/main.py
1 group1 6
2 group3 1
3 group2 8
>>>(eg:group1)group3
h1 192.168.179.133
>>>put from_windows.py
put sucesss
>>>
>>>ls
------------------------192.168.179.133------------------------
anaconda-ks.cfg
database_test
from_windows.py
install.log
install.log.syslog
m
oot
\root
tmp\from_windows.py
 
>>>

上傳前沒有from_windows.py文件,上傳後就有了!

 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

更多詳解python之簡單主機批量管理工具相關文章請關注PHP中文網! 詳解python之簡單主機批次管理工具

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn