Python route-Jobs: Class Farbic host hypervisor (for reference only)

Source: Internet
Author: User

First, the operation needs

1. Run the program to list host groups or hosts
2. Select the specified host or group
3. Choose to have the host or host group execute commands or transfer files to them (upload/download)
4. Make full use of multi-threaded or multi-process
5. Different host user name password, port can be different

Second, realize the function
1. Create a host
2. Running the program lists the host list
3. Select a designated host or group
4. Choose to have the master or host group execute commands or transfer files
5. Full use of multithreading Note: The new user to use this program 1, the creation of the host-------> to be based on their own now open host to create a host, the host information in the form of files saved;
                      2, connecting the host-------> According to the user-created host, read the DB directory using the host information, return the form of the list, and try to connect, the connection success status is set to 1, the connection is not successful status is set to 0;
3, running the host-------> According to the previous step identified can be connected to the host, the Output class connection host list, according to the user's Choice and command input to control the host
Put upload file method------> upload the local file under LocalHost, and only the input file name can be
The path of the file is saved only with the directory and file name "/downloads/aaa", and the program automatically adds the "/username" prefix path
Get upload file method------> The path of the files downloaded from the remote host only with the input directory and file name "/DOWNLOADS/AAA", the program will automatically add "/username" prefix path
Downloaded files are saved by default under localhost
Iii. Description of the catalogue
Class Farbic host hypervisor/|--bin/|   | --__init__.py|   | --para_start.py                #程序启动的主入口 | | --conf/|   | --__init__.py|   | --settings.py              #配置文件 | | --db/                             #主机数据目录 | | --lib/|   | --__init__.py|   | --common.py                 #公共方法程序 |   | --main.py                   #主程序 | | --localhost/                       #模拟本地文件目录 |   | --Aaa.jpg| | --log/|   | --Log_sys.log                #日志文件 | | --Flowchart |--README.txt
Iv. flowchart

V. Program code 1, bin/para_start.py
Import Os,sysbase_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (Base_dir) from Lib.main import main_funcif __name__ = = ' __main__ ':    main_func ()
2, conf/settings.py
Import Osbasedir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Host_info = Os.path.join (Basedir, "DB" ) Host_dir = Os.path.join (Basedir, "home") Local_dir = Os.path.join (Basedir, "localhost") Log_dir = Os.path.join (Basedir, "Log")
3, lib/common.py
Import logging,os,sysframe = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) Sys.path.append (frame) From conf import settings#def sys_logging (content,levelname): "Program logging function:p Aram Content: Contents of the log:p Aram Leveln Ame: Log level: Return:none "_filename = Os.path.join (settings. Log_dir, "Log_sys.log") log = Logging.getlogger (_filename) logging.basicconfig (filename=_filename,level=logging. info,format= '% (asctime) s-% (levelname) s-% (message) s ', datefmt= '%m/%d/%y%i:%m:%s%p ') if levelname = = ' Debug ': Lo Gging.debug (content) elif LevelName = = ' Info ': logging.info (content) elif LevelName = = ' Warning ': Logg Ing.warning (content) elif LevelName = = ' ERROR ': logging.error (content) elif LevelName = = ' critical ': l    Ogging.critical (content) def show (Msg,msg_type): "Program different information print font color:p Aram msg: Print information:p Aram Msg_type: Types of printed information : Return:none "if msg_type = =" Info ": show_msg =" \033[1;35m%s\033[0m "%msg    elif Msg_type = = "Error": show_msg = "\033[1;31m%s\033[0m"%msg elif Msg_type = = "MSG": Show_msg = " 33[1;37m%s\033[0m "%msg else:show_msg =" \033[1;32m%s\033[0m "%msg print (show_msg) sys_logging (msg, Msg_typ E
4, lib/main.py
Import Os,sys,pickle,threading,paramikofar_dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) lib_ dir = Os.path.dirname (Os.path.abspath (__file__)) sys.path.append (Lib_dir) sys.path.append (far_dir) from common import Showfrom conf Import settingsdef creat_host (): ' Creat a new host method:return:none ' ' hostname = INP UT ("Please enter hostname:>>>"). Strip () port = input ("Enter host port number:>>>"). Strip () Username = input ("Enter the login user name: >>& gt; ").        Strip () PSD = input ("Please enter login password:>>>"). Strip () Host_dic = {"hostname": hostname, "port":p ort,    "Username": Username, "PSD":p SD, "status": 0} Host_dir = settings.    host_dir+ "/" +hostname if Hostinfo_write (host_dic,hostname): Show ("Host created successfully", "error") def host_connect (): " Connect host Method:return:none "hostinfo_list = Hostinfo_read () If Len (hostinfo_list) = = 0:exit (   "Currently no hosts, please create a host") Print ("\033[1;37m host list \033[0m". Center (40, "-")) For the DIC in hostinfo_list:show ("\ t hostname:%s"%dic["hostname"], "msg") TH = Threading. Thread (target=ssh_parse,args= (DIC,)) Th.setdaemon (True) Th.start () Th.join () def ssh_parse (DIC): ' ' Try to connect all host,if can ' t connect, make it's status to 0, else to 1:p Aram Dic:host info dic:return:n One ' ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Try:ssh.connect (hostname=dic["hostname"],port=int (dic["Port"), username=dic["username"],passwo  rd=dic["PSD"]) except Exception as E:show ("host [%s] connection failed \ t reason:%s"% (dic["hostname"],e), "error") dic["status"] = 0 Hostinfo_write (dic, dic["hostname"]) else:show ("host [%s] successfully connected"% (dic["hostname"]), "a") dic["s Tatus "] = 1 hostinfo_write (dic,dic[" hostname "]) ssh.close () def run_host (): ' Try to operate Host:ret Urn:none "active_list = [] hostinfo_list = Hostinfo_read () for DiC in HoStinfo_list:if dic["status"] = = 1:active_list.append (DIC) # print (active_list) If Len (active_lis t) = = 0:exit ("Currently no connected host, please first connect the host to ensure that the main function is connected properly") Show ("Connected Host:", "MSG") for I,j in Enumerate (active_list): Sho W ("%s:%s"% (i+1,j["hostname"), "msg") Choice = input ("Enter the host you want to manipulate (enter" All ", and all hosts run simultaneously):>>>"). Strip () If choice = = "All": Host_parse (active_list) else:list = [] List.append (active_list[int (choice)-1]) Ho St_parse (list) def host_parse (list): "If host can be connected, user can input Conmand, and host would carry out T He conmand:p Aram List:all host Info List:return:none "while True:command = input (" Please enter the instructions (Help display return):>>> "). Strip () if command = =" Help ": Help_info ="-----------"Help"-----------1, input " Put "Upload file 2, enter" get "Download file 3, enter" DF "to view disk information 4, enter" LS "view file or directory 5, enter" uname "View system Information 6, enter" ifconfig "View network information 7, more commands See" HT Tp://www.cnblogs.com/japHi/p/7084042.html "'" Show (Help_info, "msg") elif command = = "Put": DIR = input ("Please enter the file name you want to upload (the default file path is---localhost):>>>"). Strip () Local_dir = settings. Local_dir + "/" + DIR If not os.path.exists (Local_dir): Show ("File name does not exist", "error") dir0 = Input ("Please enter the path you want to save (example:/DOWNLOADS/BBB):>>>"). Strip () for dic in list:th = threading. Thread (Target=put_method, args= (DIC, Local_dir, Dir0,)) Th.start () th.join () elif com Mand = = "Get": Dir1 = input ("Please enter the path to the remote host file you want to download (example:/TEMP/CCC):>>>"). Strip () Res_list = Dir1.sp Lit ("/") Local_dir = settings. Local_dir + "/" + Res_list[len (res_list)-1] # print (local_dir) for DIC in list:th = Threading.    Thread (Target=get_method, args= (DIC, Dir1, Local_dir,)) Th.start () Th.join ()    elif Command = = "B": Break else:for dic in list:th = threading. Thread (Target=command_method, args= (DIC, Command,)) Th.start () Th.join () def put_method (dic,l Ocal_dir,dir): ' Upload file method:p Aram dic:host info dic:p Aram local_dir:the dir of local file:p a Ram Dir:the dir of the file would be Savede:return:none "Try:nonlocal_dir ="/"+ dic[" username "+ Dir print (nonlocal_dir) transport = Paramiko.        Transport ((dic["hostname"], int (dic["port"])) Transport.connect (username=dic["username"], password=dic["PSD"]) SFTP = Paramiko. Sftpclient.from_transport (transport) Sftp.put (Local_dir, Nonlocal_dir) Show ("host [%s] uploaded file succeeded"% dic["hostname"] , "info") except Exception as E:show ("host [%s] Error:%s"% (dic["hostname"], E), "error") def get_method (Dic,dir, Lo Cal_dir): ' Downloads file method:p Aram Dic:host info:p Aram Dir:the dir of file to be downloads:p Aram local_dir:the dir of the file would be Saved:return:none ' tr Y:nonlocal_dir = "/" + dic["username"] +dir transport = Paramiko.        Transport ((dic["hostname"], int (dic["port"])) Transport.connect (username=dic["username"], password=dic["PSD"]) SFTP = Paramiko. Sftpclient.from_transport (transport) Sftp.get (Nonlocal_dir, Local_dir) Show ("host [%s] download file succeeded"%dic["hostname"], "    Info ") except Exception as E:show (" host [%s] Error:%s "% (dic[" hostname "],e)," error ") def command_method (Dic,command):    "' Carry out the command which user input:p Aram dic:host info:p Aram command:the conmand of user input : return: ' Try: # print (dic) ssh = Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) # Print (hostname=dic["hostname"), Port=int (dic["Port"], username=dic["username"], password=dic["p SD "]) Ssh.connect (hostname=dic[" hosTname "], Port=int (dic[" Port "]), username=dic[" username "], password=dic[" PSD "]) stdin, stdout, Sterr = Ssh.exec_comm and command result = Stdout.read () print (Result.decode ()) except Exception as E:show ("host [%f] Error :%s "% (dic[" hostname "],e)," error ") def dir_read (dirname): ' Read the dir of DB:p Aram Dirname:diename:return : Files "for roots,dirs,files in Os.walk (dirname): Return filesdef Hostinfo_write (host_dic,hostname): ' "Write the host info into a file:p Aram Host_dic:host info dict:p Aram Hostname:host name:return:if suce Ssfully return True "' Hostfile = settings. host_info+ "/" +hostname with open (Hostfile, "WB") as F:f.write (Pickle.dumps (host_dic)) return Truedef host Info_read (): ' Read the host Info:return:host info list ' ' hostinfo_list = [] for file in OS.LISTDI R (Settings. Host_info): filename = settings. host_info+ "/" +file Hostinfo_list.append(Pickle.load (open (filename, "RB")) # print (hostinfo_list) return hostinfo_listdef Main_func (): "' Main functi On:return:none "Menu_dic = {" 1 ": Creat_host," 2 ": Host_connect," 3 ": run_host} menu_info ="-----Welcome to the Fabric Master        Machine Management Interface-----1, new host 2, connect host 3, run host 4, exit program ' while True:show (menu_info, "info")            Choice = input ("What do you want to do:>>>"). Strip () if Choice.isdigit () and 0 < int (choice) <= len (menu_dic):            Menu_dic[choice] () elif Choice = = "4": Show ("Exit program", "error") Break else: Show ("Input Error", "error")

  

 

Python route-Jobs: Class Farbic host hypervisor (for reference only)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.