Python10 job idea and source code: Class Fabric host Management Program Development (for reference only), python10fabric

Source: Internet
Author: User
Tags ssh port

Python10 job idea and source code: Class Fabric host Management Program Development (for reference only), python10fabric

 

Class Fabric host Management Program Development 1, job requirements

1. Run the program to list the Host group or host list (completed)

2. Select the specified host or host group (completed)

3. Select a host or host group to transfer files (upload/download) (completed)

4. Make full use of multithreading or multi-process (completed)

5. Different host user names, passwords, and ports can be different (completed)

6. You can publish commands to hosts or host groups in batches (completed)

7. Multiple operation commands can be executed at a time (completed)

2. program file list

 

3. program flow diagram

 

 

4. Sample program testing

 

 

 

 

 

5. Program core source code
#! Usr/bin/env python #-*-coding: UTF-8-*-# auther: Mr. chen # Description: it can only run in MacOS or linux systems, such as import OS, sys, pickle, timeimport paramiko, and threadingsys. path. append ('.. ') PATH = OS. path. dirname (OS. path. abspath (_ file _) PUT_PATH = PATH. replace ('core', 'Folder/') GET_PATH = PATH. replace ('core', 'Download/') CONF_PATH = PATH. replace ('core', 'conf/') semaphore = threading. boundedSemaphore (1) # process lock def new_Host (): while True: ho Stname = raw_input ("Enter the server host name (input n = return to the upper level):") if OS. path. exists (CONF_PATH + hostname + '_ conf'): print ("the host name already exists. Please enter it again! ") Continue if hostname = 'N': return port = raw_input (" Enter the server's ssh port number (input n = return to the upper-level ):") if port = 'N': return username = raw_input ("Enter the login username (input n = return parent):") if username = 'N ': return password = raw_input ("Enter the user's password (input n = return the upper level):") if password = 'N': return dic = {'hostname': hostname, # host name 'Port': port, # port 'username': username, # username 'Password': password, # password 'status': 0 # status (0: not activated 1: activated 2: failed to activate)} if OS. pa Th. isdir (GET_PATH + hostname) = False: command = 'mkdir' + GET_PATH + hostname OS. system (command) re = hostmessage_Write (dic) if re = True: return else: print ("failed to store host information. Check the cause! ") Def delete_Host (): List = Traverse_folder () while True: dic ={} num = 0 print (" the List of existing hosts is as follows: ") for I in List: print ("{0}, Host Name: {1 }". format (str (num + 1), I) dic [str (num + 1)] = I num + = 1 choose = raw_input ("enter the host index you want to delete (input n = return upper level):") if choose = 'N ': return elif choose in dic: hostname = dic [choose] command = 'rm-F' + CONF_PATH + hostname + '_ conf' OS. system (command) print ("deleted successfully! ") Break else: print (" your input is incorrect! ") Def auto_activeHost (): text =" "warning! The program is ready to enable the multi-thread mode to activate the host. Make sure that: 1. The remote server is enabled. 2. The DNS or local hosts ing can resolve the remote server host name "" while True: print (text) choose = raw_input ("are you sure you want to activate the remote host (y/n )?: ") If choose = 'N': return elif choose = 'y': break else: print (" your input is incorrect! ") Print (" the program starts to automatically activate the remote host. Please wait... ") List = Traverse_folder () if len (List) = 0: print (" Create a host first! ") Return for I in List: dic = hostmessage_Read (I) t = threading. thread (target = auto_Active, args = (dic,) # create a multithreaded object t. setDaemon (True) # Set the object to the daemon t. start () # start the while threading thread. activeCount ()! = 1: # Number of active threads pass else: print ("activation of all hosts is complete! ") Time. sleep (2) def auto_Active (dic): ssh = paramiko. SSHClient () # create an ssh object ssh. set_missing_host_key_policy (paramiko. autoAddPolicy () # Allow connection to a host that is not in the know_hosts file try: ssh. connect (hostname = dic ['hostname'], port = int (dic ['Port']), username = dic ['username'], password = dic ['Password'], timeout = 10) failed t Exception, e: print ("Host Name: {0} failed to activate the host! Cause of failure: {1 }". format (dic ['hostname'], e) dic ['status'] = 2 hostmessage_Write (dic) else: print ("Host Name: {0} host activated successfully! ". Format (dic ['hostname']) dic ['status'] = 1 hostmessage_Write (dic) finally: ssh. close () def remote_Host (): List = Traverse_folder (key = 'status', value = 1) if len (List) = 0: print ("Activate the host first! ") Return while True: dic ={} print (" activated HOST: ") num = 0 for I in List: print (" {0}, Host Name: {1 }". format (str (num + 1), I) dic [str (num + 1)] = I num + = 1 choose = raw_input ("Enter the index of the host you want to manipulate (multiple options can be selected, n = return to the upper level):") if choose = 'N ': return choose = list (set (choose) # repeat if set (choose) & set (dic. keys () = set (choose): LIST = [] for I in choose: LIST. append (dic [I]) remote_Host_control (LIST) else: print ("your input is incorrect! ") Def remote_Host_control (List): help =" help prompt: 1. the program's Folder directory is the local file directory 2, input put to upload files to the remote host 3, input get to download files to the remote host 4, run the "while True: print (" {0} hosts are being controlled, as follows :". format (len (List) for I in List: print ("Host Name: {0 }". format (I) command = raw_input ("Enter the command you want to execute (enter n = to return to the upper level, and enter help for help):> ") if command = 'N': return elif command = 'help': print help elif command = 'get': print ("the program is preparing to download the file... ") remote_p Ath = raw_input ("Enter the absolute path of the remote server file to be downloaded (for example,/etc/hosts):") LIST = remote_path.split ('/') filename = LIST [len (LIST)-1] for I in List: local_path = GET_PATH + I + '/' + filename t = threading. thread (target = get_Method, args = (I, [remote_path, local_path]) t. setDaemon (True) t. start () while threading. activeCount ()! = 1: pass else: print ("command execution completed! ") Elif command = 'put': print (" the program is preparing to upload a file... ") while True: filename = raw_input (" Enter the file name of the file to be uploaded: ") if OS. path. exists (PUT_PATH + filename) = False: print ("the file is not found. Please enter it again! ") Continue local_path = PUT_PATH + filename remote_path = raw_input (" Where do you want to save the file to the remote server? (For example:/etc/): ") remote_path = remote_path + '/' + filename for I in List: t = threading. thread (target = put_Method, args = (I, [local_path, remote_path]) t. setDaemon (True) t. start () while threading. activeCount ()! = 1: pass else: print ("command execution completed! ") Break else: for I in List: t = threading. thread (target = execute_Command, args = (I, command) t. setDaemon (True) t. start () while threading. activeCount ()! = 1: pass else: print ("command execution completed! ") Def put_Method (hostname, Path): dic = hostmessage_Read (hostname) transport = paramiko. transport (hostname, int (dic ['Port']) try: transport. connect (username = dic ['username'], password = dic ['Password']) sftp = paramiko. SFTPClient. from_transport (transport) sftp. put (Path [0], Path [1]) failed t Exception, e: print ("Host Name: {0}, Upload Failed! Error cause: {1 }". format (hostname, e) else: pass finally: transport. close () def get_Method (hostname, Path): dic = hostmessage_Read (hostname) transport = paramiko. transport (hostname, int (dic ['Port']) try: transport. connect (username = dic ['username'], password = dic ['Password']) sftp = paramiko. SFTPClient. from_transport (transport) sftp. get (Path [0], Path [1]) failed t Exception, e: print ("Host Name: {0}, download failed! Error cause: {1 }". format (hostname, e) else: pass finally: transport. close () def execute_Command (hostname, command): dic = hostmessage_Read (hostname) ssh = paramiko. SSHClient () ssh. set_missing_host_key_policy (paramiko. autoAddPolicy () try: ssh. connect (hostname = hostname, port = int (dic ['Port']), username = dic ['username'], password = dic ['Password']) command_list = command. strip (). split (';') has t Exception, e: semapho Re. acquire () # print ("Host: {0} connection exception: {1 }". format (hostname, e) semaphore. release () # return for com in command_list: stdin, stdout, stderr = ssh.exe c_command (com) error = stderr. read () output = stdout. read () semaphore. acquire () # enable the process lock if len (error )! = 0: print ("Host: {0} An error occurred while executing the {1} command: {2}". format (hostname, com, error) if len (output )! = 0: print ("Host: {0}, the result of executing the {1} command is as follows :". format (hostname, com) print (output) semaphore. release () # process lock release def Traverse_folder (key = None, value = None): ''' traverses all the files in a folder according to the conditions, find the file that meets the conditions and return the LIST that contains the host name. If it is unconditional, return the LIST that contains all the host names: return: List ''' LIST = [] LIST = OS. listdir (CONF_PATH) for I in List: if I = '_ init __. py 'or I =' _ init __. pyc': continue else: with open (CONF_PATH + I, 'R') as f: dic = pickle. load (f) if key! = None: if dic [key] = value: LIST. append (dic ['hostname']) else: LIST. append (dic ['hostname']) return LISTdef hostmessage_Write (dic): with open (CONF_PATH + dic ['hostname'] + '_ conf', 'w') as f: pickle. dump (dic, f) return Truedef hostmessage_Read (hostname): if OS. path. exists (CONF_PATH + hostname + '_ conf'): with open (CONF_PATH + hostname +' _ conf', 'R') as f: dic = pickle. load (f) return dicdef Main (): text = "Welcome Go to Fabric host management interface 1, create host 2, delete host 3, automatically activate all hosts 4, start remote control 5, exit program "" while True: print text choose = raw_input ("Enter your choice:") dic = {'1': new_Host, '2': delete_Host, '3': auto_activeHost, '4 ': remote_Host, '5': Exit} if choose in dic: dic [choose] () else: print ("your input is incorrect! ") Def Exit (): print (" Exit! ") Exit () if _ name _ =" _ main _ ": Main ()

 

 

 

Related Article

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.