Previously implemented some simple interactive operations with Pexpect, such as the following login operation:
Import Pexpect
simulators={' 10.10.10.10 ': ' root ' }
users={' testuser ': ' 1101 '}
Child = Pexpect.spawn ('ssh [email protected]'+simulator) I= Child.expect (['[Pp]assword:','continue connecting (yes/no)?','#'])ifi = =0:child.sendline (Simulators[simulator])elifi = = 1: Child.sendline ('Yes') Child.expect ('[Pp]assword:') Child.sendline (Simulators[simulator])elifi = = 2: PassElse: Print('Login failed')
The expect method can be used to wait for a specific output to be produced in a subroutine, and then to make a specific response that throws Pexpect if the desired string is not present. Timeout exception.
If I want to add a group or user, I want to first determine whether there are groups in the system, if so, I will add users to this group, if not, I will create, and then add the user:
Child.sendline ('Cat/etc/group | grep teams:') Child.expect ('Teams:') Child.expect ('#')if 'Teams:' inchChild.before:Print('Group teams existed, continue to add users')Else: Child.sendline ('groupadd-g 1100 Teams') Child.expect ('#') Child.sendline ('Cat/etc/group | grep teams:') Child.expect ('Teams:') Child.expect ('#') if 'Teams:' inchChild.before:Print('Group teams added for%s successfully'%(simulator))Else: Print('Group teams added failed, check on simulator%s manually, go to next simulator'%simulator)continue
< Span style= "COLOR: #800000" >
"command in Linux
openstack12:/# Cat/etc/group | grep teams
teams:!:1100:
openstack12:/#
' '
Description
Child.expect ('teams:') matches the command and the first teams in the command, that is, the teams in ' Cat/etc/group | grep teams ', the child at this time. Before is the first line of ' cat/etc/group | grep ', so I continue to do a child.expect (' # '), ' # ' matches the last line of ' # ', At this point, the Child.before contains the first line teams the back of the carriage return and the second and third row of all, and then the Child.before to make a judgment:)
Use Pexpect to make simple output judgments