Python interacts with the H3C 5024E switch to obtain the switch configuration information
# Coding: utf8import re, sysimport pexpect # enable/disable debug modeDEBUG = False def telnet_login (ip, pwd, cmd, ps): child = pexpect. spawn ('telnet % s' % ip) # Whether to enable DEBUG mode. The default value is False. if DEBUG is enabled after DEBUG = True is set above: print '[' + '-' * 30 + "debug info start" + '-' * 30 + "] \ n" child. logfile_read = sys. stdout # telnet output to standard output child. CT ('(? I) Password: ', timeout = 2) # match Password:, note that there is a space child after the question mark. send (pwd + '\ R') # enter the password and press enter (\ r) Here. Do not use the sendline method child. reset CT ('Please press ENTER. \ r \ n', timeout = 1) child. send ('\ R') # follow the preceding prompt and press enter to continue the child operation. secondary CT (ps [0], timeout = 2) # match the 1st prompt child. send ('System-view' + '\ R') # enter the system-view child. secondary CT (ps [1], timeout = 2) # match the output = "" out = "" for tcmd in cmd: child. send (tcmd + '\ R') # Run the command child. secondary CT (Tcmd + '\ R') # match command echo child. reverse CT (ps [1], timeout = 2) # After the matching command is executed, the prompt out = child. before # capture command output results if out! = '': Out = re. sub ('. *\[. * ', '', out) # tail prompt for processing output results out = re. sub ('\ 015', '', out) # process the output result tail ^ M (actually a carriage return) output + =" \ n "+ tcmd +" execution result: \ n "+" \ n ". join ([j. strip () for j in out. split ('\ n') if j! = '']) # Delete unnecessary blank lines and spaces at the beginning and end of the line in the Command output. return child, output if _ name _ = '_ main __': host = "192. 168. *. * "password =" ###### "command = ['dis ip', 'dis arp '] # Run the command list prompt = [' \) \> ', '\) \]'] # prompt c, export stdout = telnet_login (host, password, command, prompt) # after debug is enabled, you can also write the command output result to the file if DEBUG: with open ("/tmp/telnet_output.txt", "w") as f: f. write (writable stdout) print '\ n [' + '-' * 30 + "debug info end" + '-' * 30 + "] \ n" print '[' + '-' * 30 + "telnet command output" + '-' * 23 + "] \ n" print into stdout # print command execution result c. close (force = True) # Note: c and syststdout are used to receive the child and output returned by the telnet_login function.