Today's job involves a process, then use the job to illustrate the use of the process:
Here we define 2 functions Getparamikocmd and Batchcmd, which are used to send SSH commands to the remote server in bulk and return the execution results.
Execute batchcmd for some user interaction and parameter acquisition (here is a set of server grouping information), the loop initiation process executes the SSH command in bulk, each process calls the Getparamikocmd function for SSH command execution.
Processes are independent of each other, and data does not share with each other, so that it can accomplish its tasks independently without affecting each other.
defGetparamikocmd (groupname,servername,ip,port,username,passwod,cmd,lock):" "called by process: Process bulk SSH command:p Aram GroupName::p Aram serverName::p Aram IP::p Aram Port::p Aram Username::p Aram Passwod::p Aram cmd::p Aram Lock:: return:" " #Lock.acquire ()Objparamiko = Myparamiko (PARAMIKO,IP,PORT,USERNAME,PASSWOD)#Create an instance that handles ParamikoResult,stdin,stderr = Objparamiko.sshclienthandle (cmd)#get the SSH client handle Print("server Group {}---server name: {}:\n{}\n*******************************************************". Format (GROUPNAME,SERVERNAME,STR (result,'Utf-8')))#Print the Read information #lock.release () #return Result,stdin,stderrdefBatchcmd (servergroupdict):" "Batch command handlers, Menu 2:p Aram servergroupdict: Server group Information dictionary: return:" " #print ("Batchcmd")Cmdlist =[] GroupName="'ServerName=[] inpwho= Input ("to send commands to all groups, enter the command: ' all ' \ n or enter ' server group name (for example: group1) ' to send a command to a group") Inpcmd= Input ("Send command >>>\n") Lock=Lock ()ifinpwho = =' All':#send information to all server group members forKvinchServergroupdict.items ():#Traverse Group NameGroupName =k forK1,v1inchV.items ():#Traverse server name, generate server parameter listservername.append (K1) cmdlist.append (v1) forIinchRange (len (cmdlist)):#Traverse Server parameter listiport = Int (cmdlist[i][1])#Port to Integer #process Start, delivery: Group name, server name, IP port user password, command
p = Process (target=getparamikocmd,args= (groupname,servername[i],cmdlist[i][0],iport,cmdlist[i][2],cmdlist[i][3), Inpcmd,lock)) P.start ()#START Processp.join () cmdlist=[] ServerName= [] Else:#Select group forKvinchServergroupdict.items ():ifinpwho = =K:groupname=k forK1,v1inchV.items (): Servername.append (K1) cmdlist.append (v1) forIinchRange (len (cmdlist)):#Traverse Server parameter listiport = Int (cmdlist[i][1])#Port to Integerp = Process (target=Getparamikocmd, args= (Groupname,servername[i],cmdlist[i][0],iport,cmdlist[i][2],cmdlist[i][3],inpcmd,lock))#generates a Process object, inpcmd the command to be executedP.start ()#START Processp.join () cmdlist=[] ServerName= []
Python automation development from shallow into deep-advanced (process)