Python開發程式:簡單主機批量管理工具,python開發

來源:互聯網
上載者:User

Python開發程式:簡單主機批量管理工具,python開發

題目:簡單主機批量管理工具

需求:

 

流程圖:

說明:

### 作者介紹:* author:lzl### 部落格地址:* http://www.cnblogs.com/lianzhilei/p/5881434.html### 功能實現題目:簡單主機批量管理工具 需求: 主機分組 登入後顯示主機分組,選擇分組後查看主機列表 可批量執行命令、傳送檔案,結果即時返回 主機使用者名稱密碼可以不同### 目錄結構: Host-Manage │ ├── ftpclient #用戶端程式 ├── README.txt ├── management.py #服務端入口程式 ├── database #資料庫 ├── test.py #修改資料庫### 注釋 可批量執行命令、傳送檔案 上傳命令格式: put database /tmp/db### 運行環境 windows系統 python3.0+README

 

主程式

#!/usr/bin/env python# -*- coding:utf-8 -*-#-Author-Lianimport jsonimport paramikoimport threadingclass Remotehost(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 command(self):        #擷取命令        ssh = paramiko.SSHClient()        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())   # 允許串連不在know_hosts檔案中的主機        ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.password)   # 串連伺服器        stdin, stdout, stderr = ssh.exec_command(self.cmd)              # 擷取命令結果        res ,err = stdout.read(),stderr.read()              # 三元運算        result = res if res else err        print("[%s]".center(50,"-")%self.host)        print(result.decode())                                      # 列印輸出        ssh.close()    def put(self):        #上傳        try:            transport = paramiko.Transport((self.host, self.port))            transport.connect(username=self.username, password=self.password)            sftp = paramiko.SFTPClient.from_transport(transport)            sftp.put(self.cmd.split()[1], self.cmd.split()[2])              # 上傳檔案            transport.close()            print("\033[32;0m【%s】 上傳 檔案【%s】 成功....\033[0m"%(self.host,self.cmd.split()[2]))        except Exception as error:                                # 抓住異常            print("\033[31;0m錯誤:【%s】【%s】\033[0m"%(self.host,error))    def run(self):        #反射        cmd_str = self.cmd.split()[0]        if hasattr(self,cmd_str):            getattr(self,cmd_str)()        else:            setattr(self,cmd_str,self.command)            getattr(self,cmd_str)()if __name__ == "__main__":    #主程式    with open("database","r") as file:        data_dict = json.loads(file.read())     #擷取資料庫資訊    for k in data_dict:                        #列印地址組        print(k)    group_choice = input("輸入要操作的組名:").strip()    if data_dict.get(group_choice):        host_dict = data_dict[group_choice]     #定義主機字典        for k in host_dict:                    #列印所選地址組所有的主機名稱            print(k)        while True:            cmd = input("選擇進行的操作的命令:").strip()            thread_list=[]            if cmd:                                 #命令不為空白                for k in host_dict:                    host, port, username, password=k,host_dict[k]["port"],host_dict[k]["username"],host_dict[k]["password"]                    func = Remotehost(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:        print("\033[31;0m操作組不存在\033[0m")

 

資料庫:

{"group1": {"192.168.20.217": {"password": "123456", "username": "root", "port": 22}, "192.168.20.219": {"password": "zyw@123", "username": "root", "port": 22}}, "group2": {"192.168.20.217": {"password": "123456", "username": "root", "port": 22}}}database

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.