def _spawn_corenlp(self): if VERBOSE: print self.start_corenlp if use_winpexpect: self.corenlp = winpexpect.winspawn(self.start_corenlp, maxread=8192, searchwindowsize=80) else: self.corenlp = pexpect.spawn(self.start_corenlp, maxread=8192, searchwindowsize=80) # show progress bar while loading the models if VERBOSE: widgets = ['Loading Models: ', Fraction()] # Model timeouts: # pos tagger model (~5sec) # NER-all classifier (~33sec) # NER-muc classifier (~60sec) # CoNLL classifier (~50sec) # PCFG (~3sec) timeouts = [20, 200, 600, 600, 20] for i in xrange(5): self.corenlp.expect("done.", timeout=timeouts[i]) # Load model pbar.update(i + 1) self.corenlp.expect("Entering interactive shell.") pbar.finish() # interactive shell self.corenlp.expect("\nNLP> ")
def test_expect(self): ps = winspawn('powershell.exe -command -') ps.sendline('Get-Location') ps.expect('---\s+\r\n') cwd = ps.readline().strip() assert os.getcwd() == cwd ps.terminate()
def _spawn_corenlp(self): if VERBOSE: print self.start_corenlp if use_winpexpect: self.corenlp = winpexpect.winspawn(self.start_corenlp, maxread=8192, searchwindowsize=80) else: self.corenlp = pexpect.spawn(self.start_corenlp, maxread=8192, searchwindowsize=80, timeout=120) # show progress bar while loading the models if VERBOSE: pass # widgets = ['Loading Models: ', Fraction()] # pbar = ProgressBar(widgets=widgets, maxval=5, force_update=True).start() # Model timeouts: # pos tagger model (~5sec) # NER-all classifier (~33sec) # NER-muc classifier (~60sec) # CoNLL classifier (~50sec) # PCFG (~3sec) # timeouts = [20, 200, 600, 600, 20] # for i in xrange(5): # self.corenlp.expect("done.", timeout=timeouts[i]) # Load model # # pbar.update(i + 1) # self.corenlp.expect("Entering interactive shell.") # pbar.finish() # interactive shell self.corenlp.expect("\nNLP> ") print "Done"
def spawn(self, *cmd): try: if settings.host_os == 'windows': self.__ui_str = 'Windows host CMD' self.__dut = winspawn(*cmd) elif settings.host_os == 'linux': self.__ui_str = 'Linux host Bash shell' self.__dut = pexpect.spawn(*cmd, encoding='utf-8') cmd = ''.join(*cmd) UI.log('ACTION', 'Executing command on ' + self.__ui_str, 'Command: ' + cmd) UI.logTitle('TERMINAL OUTPUT from ' + self.__ui_str) UI.last_ui = str(self) last_line = self.__last_buff.split('\n')[-1] UI.log_stream.write(last_line) if settings.glb.print_to_stdout: sys.stdout.write(last_line) UI.end_msg = False except Exception as e: if not settings.glb.print_to_stdout: sys.stdout.write( 'CRITICAL ALERT: Host spawn session failed to initialize') sys.stdout.write(str(e)) UI.log('CRITICAL ALERT', 'Host spawn session failed to initialize', str(e)) self.__dut = None
def test_wait(self): ps = winspawn('powershell.exe -command -') ps.sendline('Sleep 2; Exit') ps.wait() assert not ps.isalive() assert ps.exitstatus == 0 ps.terminate()
def test_telnet(): child = winspawn("C:/users/jason.li/Downloads/apps/plink.exe -telnet 127.0.0.1 -P 23") assert child.isalive() child.logfile = sys.stdout # wait until the prompt index = child.expect(["[A-Z]+>", TIMEOUT, EOF], timeout = 10) if index != 0: child.terminate() exit() print "The return index is %d" % index print "child process is alive ?", child.isalive() child.sendline("znspace \"VISTA\"\r\n") index = child.expect(["VISTA>", TIMEOUT, EOF], timeout = 10) if index != 0: child.terminate() exit() child.sendline("D ^XINDEX") child.expect("All Routines?") child.sendline("NO") child.expect("Routine:") child.sendline() child.expect("Select BUILD NAME") child.sendline() child.expect("Select PACKAGE NAME") child.sendline() index = child.expect(["VISTA", TIMEOUT, EOF], timeout=10) print index child.sendline("HALT") child.terminate()
def test_terminate(self): ps = winspawn('powershell.exe -command -') assert ps.isalive() ps.terminate() assert not ps.isalive() assert ps.exitstatus != 0 ps.terminate()
def test_dircommand(): logFile = StringIO.StringIO() child = winspawn("dir", logfile=logFile) index = child.expect([">>>", TIMEOUT, EOF]) print index print logFile.getvalue() child.terminate()
def test_python(): logFile = StringIO.StringIO() child = winspawn("c:\Python27\python.exe", logfile=logFile) index = child.expect([">>>", TIMEOUT, EOF]) print index print logFile.getvalue() child.terminate()
def createConnection(self, command, username = None, password = None): if not command: command = self.DEFAULT_WIN_TELNET_CMD self._connection = winspawn(command, timeout = DEFAULT_TIME_OUT_VALUE) assert self._connection.isalive() if username and password: self.__signIn__(username, password) self.__changeNamesapce__()
def initAccess(): global deviceRadio deviceRadio = [] CRValueName = [ 'STA CH', 'STA Signal', 'STA Rx', 'STA Tx', 'STA BSSID', ] print('{}-ing to {}'.format(deviceAccess, deviceIP)) if deviceAccess == 'ssh': child = winpexpect.winspawn('plink -{} {}@{} -pw {}'.format( deviceAccess, deviceUsername, deviceIP, devicePassword)) try: child.expect('>') # sleep(1) except: print( "Timeout reached: First time ssh-ing into the device/device is offline" ) #child.expect('(y/n)', timeout=3) child.sendline('y') child.expect('#|$|>', timeout=10) elif deviceAccess == 'telnet': child = winpexpect.winspawn('plink -{} {}'.format( deviceAccess, deviceIP)) sleep(1) child.expect('ogin:', timeout=10) child.send('{}\r'.format(deviceUsername)) #Need to add another line for case of password child.expect('Password:'******'{}\r'.format(devicePassword)) #child.expect('>') #child.sendline('magic') #child.expect('MAGIC>') #child.sendline('!') #child.sendline('sh') child.expect('#') else: child = '' print( 'ERROR: Please write deviceAccess label in lower case or appropriately' ) findStationMAC(child) return child
def executeScript(inputScript, scriptOptionalArgs, inputFile=None): global testcaseInfoList global testcaseInfo global yamlCont testcaseInfoList = [] yamlCont = {} if inputFile != None: fil = open(inputFile, "r") yamlCont = yaml.load(fil) # inputFileType = re.search('(.*).yaml', inputFile).group(1) inputFileType = 'unknown' if inputFile != None: inputFileType = re.search('(.*).yaml', inputFile).group(1) cmd = "%s %s" % (inputScript, ' '.join(scriptOptionalArgs)) #inputFileType = 'unknown' print "@@@@@@@@@@@@@@@" print cmd print "@@@@@@@@@@@@@@@" ps = winpexpect.winspawn(cmd) ps.logfile_read = sys.stdout ## Initialize testcaseInfo if the script is not a flist. if inputFileType in ['unknown']: scriptName = inputScript testcaseInfo = testInfo(scriptName) testcaseInfoList.append(testcaseInfo) timeout = -1 ps.interact(output_filter=scriptExecutionMonitor) if inputFileType is 'unknown': ## creates a nested suite suiteList = [] for testcaseInfo in testcaseInfoList: testcaseInfo.flush() suite = createRobotSuite(testcaseInfo) suiteList.append(suite) suite = TestSuite(inputScript) suite.suites = suiteList result = suite.run(output='output.xml', loglevel='debug') for testcaseInfo in testcaseInfoList: testcaseInfo.variableFile.close() else: ## creates a single suite for testcaseInfo in testcaseInfoList: testcaseInfo.flush() print testcaseInfo suite = createRobotSuite(testcaseInfo) result = suite.run(output='output.xml', loglevel='debug') testcaseInfo.variableFile.close() # Generating log files requires processing the earlier generated output XML. ResultWriter('output.xml').write_results() pp = postProcess.postProcess(suiteFile=testcaseInfo.scriptName) pp.close()
def initAccess(): global deviceRadio deviceRadio = [] print('{}-ing to {}'.format(deviceAccess, deviceIP)) if deviceAccess == 'ssh': child = winpexpect.winspawn('plink -{} {}@{} -pw {}'.format( deviceAccess, deviceUsername, deviceIP, devicePassword)) try: child.expect('$') #print('got ssh login') except: print( "Timeout reached: First time ssh-ing into the device/device is offline" ) #child.expect('(y/n)', timeout=3) child.sendline('y') child.expect('#|$', timeout=10) elif deviceAccess == 'telnet': child = winpexpect.winspawn('plink -{} {}'.format( deviceAccess, deviceIP)) sleep(1) child.expect('ogin:', timeout=10) child.send('{}\r'.format(deviceUsername)) #Need to add another line for case of password child.expect('Password:'******'{}\r'.format(devicePassword)) #child.expect('>') #child.sendline('magic') #child.expect('MAGIC>') #child.sendline('!') #child.sendline('sh') child.expect('#') elif deviceAccess == 'adb': child = winpexpect.winspawn('adb connect {}'.format(deviceIP)) child.expect('connected to {}:5555'.format(deviceIP)) print('adb connected') else: child = '' print( 'ERROR: Please write deviceAccess label in lower case or appropriately' ) #findStationMAC(child) setHeaders(child) return child
def executeScript(inputScript, scriptOptionalArgs, inputFile=None): global testcaseInfoList global testcaseInfo global yamlCont testcaseInfoList = [] yamlCont = {} if inputFile != None: fil = open(inputFile, "r") yamlCont = yaml.load(fil) # inputFileType = re.search('(.*).yaml', inputFile).group(1) inputFileType = 'unknown' if inputFile != None: inputFileType = re.search('(.*).yaml', inputFile).group(1) cmd = "%s %s" %(inputScript, ' '.join(scriptOptionalArgs)) #inputFileType = 'unknown' print "@@@@@@@@@@@@@@@" print cmd print "@@@@@@@@@@@@@@@" ps = winpexpect.winspawn(cmd) ps.logfile_read = sys.stdout ## Initialize testcaseInfo if the script is not a flist. if inputFileType in ['unknown']: scriptName = inputScript testcaseInfo = testInfo(scriptName) testcaseInfoList.append(testcaseInfo) timeout = -1 ps.interact(output_filter=scriptExecutionMonitor) if inputFileType is 'unknown': ## creates a nested suite suiteList = [] for testcaseInfo in testcaseInfoList: testcaseInfo.flush() suite = createRobotSuite(testcaseInfo) suiteList.append(suite) suite = TestSuite(inputScript) suite.suites = suiteList result = suite.run(output='output.xml', loglevel='debug') for testcaseInfo in testcaseInfoList: testcaseInfo.variableFile.close() else: ## creates a single suite for testcaseInfo in testcaseInfoList: testcaseInfo.flush() print testcaseInfo suite = createRobotSuite(testcaseInfo) result = suite.run(output='output.xml', loglevel='debug') testcaseInfo.variableFile.close() # Generating log files requires processing the earlier generated output XML. ResultWriter('output.xml').write_results() pp = postProcess.postProcess(suiteFile=testcaseInfo.scriptName) pp.close()
def createConnection(self, command, instance, username = None, password = None): if not command: command = self.DEFAULT_WIN_TELNET_CMD self._instance = instance self._connection = winspawn(command, timeout = DEFAULT_TIME_OUT_VALUE) assert self._connection.isalive() if username and password: self.__signIn__(username, password) self.__changeNamesapce__()
def __inittelnet__(self, ip, port, user, pwd, prompt): if port != '': self.__ui_str = 'Telnet ' + ip + ' on port ' + port else: self.__ui_str = 'Telnet ' + ip UI.log('ACTION', 'Initializing ' + self.__ui_str) try: if settings.host_os == 'windows': if port != '': spw = winspawn('bin_win32/plink -telnet ' + ip + ' -P ' + port) else: spw = winspawn('bin_win32/plink -telnet ' + ip) #spw = winspawn('bin_win32/telnet_win.exe '+ip) else: spw = pexpect.spawn('telnet ' + ip + ' ' + port, encoding='utf-8') except Exception as e: if not settings.glb.print_to_stdout: sys.stdout.write( 'CRITICAL ALERT: Telnet spawn session failed to initialize' ) sys.stdout.write( 'Please check Telnet login credentials, and verify the IP address is configured ' + 'properly.') sys.stdout.write(e) UI.log( 'CRITICAL ALERT', 'Telnet spawn session failed to initialize', 'Please check Telnet login credentials, and verify the IP address is configured properly.', str(e)) return 'FAIL' self.__dut = spw self.__prompt = prompt return self.__login__(user, pwd)
def __initssh__(self, ip, port, user, pwd, prompt): if port != '': self.__ui_str = 'SSH ' + user + '@' + ip + ' on port ' + port else: self.__ui_str = 'SSH ' + user + '@' + ip UI.log('ACTION', 'Initializing ' + self.__ui_str) try: if settings.host_os == 'windows': if port != '': spw = winspawn('bin_win32/plink -ssh ' + user + '@' + ip + ' -P ' + port) else: spw = winspawn('bin_win32/plink -ssh ' + user + '@' + ip) else: spw = pexpect.spawn( 'ssh ' + user + '@' + ip + ' -p ' + port + ' -o StrictHostKeyChecking=no -o ServerAliveInterval=60', encoding='utf-8') except Exception as e: if not settings.glb.print_to_stdout: sys.stdout.write( 'CRITICAL ALERT: SSH spawn session failed to initialize') sys.stdout.write( 'Please check SSH login credentials, and verify the IP address is configured ' + 'properly.') sys.stdout.write(e) UI.log( 'CRITICAL ALERT', 'SSH spawn session failed to initialize', 'Please check SSH login credentials, and verify the IP address is configured properly.', str(e)) return 'FAIL' self.__dut = spw self.__prompt = prompt return self.__login__(user, pwd)
def __init__(self, address, ttType, action="pos", enable="1", pos_target="0", vel_target="5000"): if ttType == 'octoscope': while True: try: self.address = address self.data = requests.get("http://{}/api/turntable".format( self.address)) self.action = action self.enable = enable self.pos_target = pos_target self.vel_target = vel_target self.ttType = ttType break except: print( 'Octoscope: A problem with establishing connection to turntable {}. Retrying again in 1 second.' .format(self.address)) sleep(1) elif ttType == 'dot11': self.ttType = ttType self.address = address self.vel_target = 'medium2' self.fileName = 'turntableControl' self.position = 0 import platform if platform.system() == 'Windows': import winpexpect self.child = winpexpect.winspawn( 'plink -{} {}@{} -pw {}'.format('ssh', 'pi', self.address, 'raspberry')) else: self.child = pexpect.spawn('{} {}@{} -pw {}'.format( 'ssh', 'pi', self.address, 'raspberry')) try: self.child.expect('$') except: print( "Timeout reached: First time ssh-ing to raspberry/raspberry is offline" ) #child.pexpect('(y/n)', timeout=3) self.child.sendline('y') self.child.expect('#|$', timeout=10) else: print( "Please enter the proper turntable type (ttType) to either dot11 or octoscope" )
def createConnection(self, command, instance, username = None, password = None, hostname=DEFAULT_HOST, port=DEFAULT_PORT): if not command: command = self.DEFAULT_WIN_TELNET_CMD if (hostname and port): command += " %s -P %s" % (hostname, port) self._instance = instance self._connection = winspawn(command, timeout = DEFAULT_TIME_OUT_VALUE) assert self._connection.isalive() if username and password: self.__signIn__(username, password) self.__changeNamesapce__()
def test_spawn_with_cwd(self): # Use a directory that is not our cwd cwd = os.getcwd() homedir = os.path.expanduser('~') if cwd != homedir: dir = homedir else: dir, tail = os.path.splitdrive(homedir) ps = winspawn('powershell.exe -command -', cwd=dir) ps.sendline('Get-Location') ps.expect('---\s+\r\n') cwd = ps.readline().strip() assert cwd == dir ps.terminate()
def start(self, **args): # On Windows 2008 R2, which is always 64-bit, the PowerShell bindings # are only installed in the 32-bit "Windows on Windows" environment. syswow = r'C:\Windows\SysWOW64' try: st = os.stat(syswow) except OSError: st = None if st and stat.S_ISDIR(st.st_mode): newpath = os.path.join(syswow, 'WindowsPowerShell', 'v1.0') newpath += os.pathsep if newpath not in os.environ['Path']: newpath += os.environ['Path'] os.environ['Path'] = newpath self.child = winspawn('powershell.exe -Command -', **args)
def __init__(self, jar_path, grammar_path): # Check input if not jar_path.endswith('.jar') or not os.path.isfile(jar_path): raise Exception("Invalid jar file") if not grammar_path.endswith('.gr') or \ not os.path.isfile(grammar_path): raise Exception("Invalid grammar file") cmd = 'java -jar %s -gr %s' % (jar_path, grammar_path) if os.name == 'nt': self.parser = winpexpect.winspawn(cmd) else: self.parser = pexpect.spawn(cmd) # Pass in a dumb sentence to fully initialize tmp = self.parse('')
def connect(user, host, password): ssh_newkey = 'Are you sure you want to continue connecting' connStr = 'ssh ' + user + '@' + host child = winpexpect.winspawn(connStr) ret = child.expect([winpexpect.TIMEOUT, ssh_newkey, '[P|p]assword:']) if ret == 0: print('[-] Error Connecting') return if ret == 1: child.sendline('yes') ret = child.expect([winpexpect.TIMEOUT, '[P|p]assword:']) if ret == 0: print('[-] Error Connecting') return child.sendline(password) child.expect(PROMPT) return child
def __init__(self, jar_path, grammar_path): """Specify the path to the parser jar file and the grammar file. """ # Check input if not jar_path.endswith('.jar') or not os.path.isfile(jar_path): raise Exception("Invalid jar file") if not grammar_path.endswith('.gr') or \ not os.path.isfile(grammar_path): raise Exception("Invalid grammar file") cmd = 'java -jar %s -gr %s' % (jar_path, grammar_path) if os.name == 'nt': self.parser = winpexpect.winspawn(cmd) else: self.parser = pexpect.spawn(cmd) # Pass in a dumb sentence to fully initialize tmp = self.parse('')
def ssh_login(user, NE_IP): host_user = '******' % (user, NE_IP) child = winpexpect.winspawn('ssh', [ '-t', '-t', '-o StrictHostKeyChecking=no', '-o UserKnownHostsFile=d:/null', host_user ]) os.remove('D:\\null') index = child.expect( ['(?i)~#', 'connect timed out', winpexpect.EOF, winpexpect.TIMEOUT]) if (index != 0): print 'Connect to %s failed' % NE_IP child.terminate(force=True) child.sendline('lsh') #"(?i)>" 期望具有>的字符出现,就返回Index=0 child.expect(['(?i)>']) #child.expect('root@mcp1800>') child.sendline('configure') #child.expect('root@mcp1800#') child.sendline('q') print 'login %s NE succeeded' % NE_IP return child
def createPackets(self, fileName): ''' Create PCAP packets. delegate work to PCAP Services Args: filename : path to pcap file ''' # projectPath = " PCAP/PCAPServices.py" # if platform.system() == 'Darwin': try: varSize = os.path.getsize(fileName) except Exception as e: print("File doesnt exist! ") return #pcap file too big to handle if (varSize >= 50e7): print("File size is huge,(" + str(varSize / 1e6) + " MB) want to proceed?[Y/N]") answer = input() if (not answer) or (answer.lower()[0] != 'y'): return # projectPath = "src/main/python/Backend/PCAP/PCAPServices.py" projectPath = "{}/{}.py".format(os.getcwd(), "PCAPServices") print(projectPath) #spawn a new process using the right library for the OS if platform.system() == "Windows": self.child = winpexpect.winspawn("python " + '"' + projectPath + '"') print("created - w ") else: self.child = pexpect.spawn("python3.6 " + projectPath, encoding='utf-8') print("created") self.child.expect("loop") print("Creating") print(fileName + " file name") #Send signal to pcapservices self.child.sendline("create " + fileName) self.child.expect("Done")
def run_recorder(expInfo): # parse in currect time and date currentTime = time.strftime('%m-%d-%y_%H-%M') # parse in participant ID subjectID = expInfo['Participant ID'] # parse in experiment mode between "train" and "neurofeedback" expMode = expInfo['Experiment Mode'] # path to LabRecorder LabrecorderPath = os.path.join(base_dir_init(), 'lib', 'LabRecorder', 'LabRecorderCLI.exe') # path to store lsl streams storePath = os.path.join(osuser_path_init(), subjectID) # run LabRecorder recorder_process = winpexpect.winspawn( '%s %s\subject_%s_%s_%s.xdf \'name="Keyboard"\'' % (LabrecorderPath, storePath, subjectID, expMode, currentTime)) return recorder_process
def test_multiple_close(self): ps = winspawn('powershell.exe -command -') ps.close() ps.close()
def test_wait_after_close(self): ps = winspawn('powershell.exe -command -') ps.close() # closes stdin and should therefore exit powershell ps.wait() assert not ps.isalive()
def test_multiple_terminate(self): ps = winspawn('powershell.exe -command -') ps.terminate() ps.terminate()
import sys timeout = 4200 baseMsg = 'plplplplplp' messages = 5 setup = None peer1 = None peer2 = None peers = int(sys.argv[1]) try: start = time.time() setup = winpexpect.winspawn('py -u setup.py -peers ' + str(peers), timeout=420) print('------------') print(str(peers) + ' peers') setup.expect('>') end = time.time() print('setup.py done') print('time: '+str(end-start)) peer1 = winpexpect.winspawn('py -u interactive_peer.py localhost 8500 peer1 10', timeout=timeout) peer2 = winpexpect.winspawn('py -u interactive_peer.py localhost 8501 peer2 10', timeout=timeout) #setup peer1 peer1.expect('>') peer1.sendline('secret private.pem') peer1.expect('>') peer1.sendline('hello') peer1.expect('>')
def test_wait_timeout(self): ps = winspawn('powershell.exe -command -') assert_raises(TIMEOUT, ps.wait, timeout=2) ps.terminate()
#!/usr/bin/python3 # you must install pexpect for this to work: # sudo apt-get install python3-pip # sudo pip3 install pexpect import time import winpexpect import re import sys timeout = 900 msg = 'plplplplplp' try: print('start: {:.2f}'.format(time.time())) setup = winpexpect.winspawn('py setup.py -peers 149 -late 0.1', timeout=30) setup.logfile = sys.stdout setup.expect('>') peer = winpexpect.winspawn('py interactive_peer.py localhost 8500 peer1 5', timeout=timeout) #setup peer1 peer.expect('>') peer.sendline('hello') peer.expect('>') time.sleep(120.0) peer.sendline('dhcard-all') peer.expect('Average Diffie-Hellman connection pool cardinality in this network: \d+.\d+\r\n') avgdhcard = re.compile('\d+.\d+').search(str(peer.after)).group() totalTime = '{:.2f}'.format(time.time()) print(totalTime + ' ' + avgdhcard) setup.terminate() peer.terminate()
channel_format='string', source_id='Keyboard') # Initialize the keyboard stream. outlet = StreamOutlet(info) currentTime = expInfo['date'] subjectID = expInfo['participant'] Labrecorder = '.\lib\LabRecorder\LabRecorderCLI.exe' Dataset='.\Dataset' # Open LabRecorder import subprocess, sys, os, winpexpect, time #os.system("start /B start cmd.exe @cmd /k .\lib\LabRecorder\LabRecorderCLI.exe .\Dataset\'currentTime'.xdf 'type=EEG'") #os.system("start /B start cmd.exe @cmd /k %s %s\%s_%s 'type=EEG'" % (Labrecorder, Dataset, currentTime,subjectID)) child = winpexpect.winspawn('%s %s\%s_%s \'name="Keyboard"\'' % (Labrecorder,Dataset,currentTime,subjectID)) # Fix random seed random.seed() # Read stimuli excel file infile = './listStim.xlsx' # Number of stimuli and number of blocks num_trials = 10 num_blocks = 8
def test_expect(): ps = winpexpect.winspawn('ping') ps.sendline('exit') print ps.before.decode('gbk') ps.terminate()
wrong_expert_pass = '******' enter_expert_pass = '******' sk1 = '\n\n\n---------------------------------------------\n' def skip(): px.send('\n') px.expect(']# ') px.send('\n') px.expect(']# ') px.send('\n') px.expect(']# ') for host in ip_addr_list: EXPECTSTUB = 'expectStub.exe' #plink px = winpexpect.winspawn('c:/python/openssh/bin/plink.exe -t ' + user + '@' + host) px = winpexpect.winspawn('c:/python/openssh/bin/plink.exe -ssh ' + user + '@' + host, timeout=6, stub=EXPECTSTUB) fout = open('c:/python/checkpoint/test_debug/{0}.txt'.format(host),"w") #px.logfile = sys.stdout px.logfile_read = fout px.expect('password:'******'1q2w3e\n') px.expect('>') px.send('expert\n') px.expect('password:'******'1q2w3e\n') px.expect('now.', timeout=10) px.send('\n') px.expect('.*Expert.*') skip() px.send('cat /etc/hosts\n') skip()
def getStatistics(siebel_server, hostServer, isFullMetrics=False): child = None isError = False try: try: result = dict() errorPrefix = 'SIEBEL_STAT ERROR| ' successPrefix = 'SIEBEL_STAT OK| ' compNameMap = dict(cgi.parse_qsl(config_props["siebel.mgmt.components.map"])) metrics_scale = dict(cgi.parse_qsl(config_props["siebel.mgmt.metrics.scale.map"])) if metrics_scale == None: metrics_scale = dict() logger.debug( "Getting stat for enterprise: %s" % (config_props["siebel.enterprise"]) ) svrmgr_call = 'srvrmgr.exe /g ' + config_props["siebel.gateway"] + ' /e ' + config_props["siebel.enterprise"] + ' /s ' + siebel_server + ' /u ' + config_props["siebel.user"] + ' /p ' + config_props["siebel.password"] svrmgr_prompt = 'srvrmgr:' + siebel_server + '>' child = winpexpect.winspawn(svrmgr_call) #time.sleep(15) logger.debug( "Checking for the prompt: %s" % (svrmgr_prompt) ) child.expect (svrmgr_prompt, timeout=120) headerMsg = child.before #Get Server status logger.info( "Getting the server status" ) child.sendline ('list servers show SBLSRVR_NAME,HOST_NAME,SBLSRVR_STATE,START_TIME,END_TIME') child.expect (svrmgr_prompt, timeout=120) stats = child.before logger.debug( stats ) serverPrefix = "Server_" oneStats = buildStatDict(stats, serverPrefix,0,2) logger.debug( oneStats ) if oneStats.get(serverPrefix+siebel_server, None) == None: return buildNagioOut(errorPrefix + serverPrefix + 'STATE=3 ', result, isError=True) serverStatus = oneStats[serverPrefix+siebel_server].upper() del oneStats[serverPrefix+siebel_server] if serverStatus != 'RUNNING': return buildNagioOut(errorPrefix + serverPrefix + 'STATE=2 ', result, isError=True) result.update(oneStats) result[serverPrefix + 'STATE'] = '0' #serverStatus components = config_props['siebel.mgmt.components.' + hostServer].split(',') taskComponents = config_props['siebel.mgmt.interactive.components.' + hostServer].split(',') #Get Components status logger.info( "Getting the component status" ) child.sendline ('list component show CC_ALIAS,CG_ALIAS,CP_DISP_RUN_STATE,CP_START_TIME,CP_END_TIME') child.expect (svrmgr_prompt, timeout=120) stats = child.before compPrefix = 'comp_' oneStats = buildStatDict(stats, compPrefix,0,2) logger.debug( oneStats ) for aSibelComp in components: aComp = compNameMap.get(aSibelComp, aSibelComp) if oneStats.get(compPrefix+aSibelComp, None) == None: return buildNagioOut(errorPrefix + compPrefix+aComp + '_STATE=3 ', result, isError=True) compStatus = oneStats[compPrefix+aSibelComp].upper() #del oneStats[compPrefix+aSibelComp] if compStatus != 'RUNNING' and compStatus != 'ONLINE': return buildNagioOut(errorPrefix + compPrefix+aComp + '_STATE=2 ', result, isError=True) logger.debug( oneStats ) #result.update(oneStats) result[compPrefix+aComp + '_STATE'] = '0' #compStatus #Get Running Tasks status for each Component logger.info( "Getting the component tasks status" ) goodpctStr = config_props["siebel.mgmt.interactive.components.goodPct"] goodpct = -1 if goodpctStr != None: goodpct = int(goodpctStr) for aSibelComp in taskComponents: aComp = compNameMap.get(aSibelComp, aSibelComp) taskPrefix = 'task_'+ aComp + '_' child.sendline ('list tasks for component ' + aSibelComp + ' show SV_NAME, CC_ALIAS, TK_PID, TK_DISP_RUNSTATE') child.expect (svrmgr_prompt, timeout=120) stats = child.before oneStats = buildStatDict(stats, taskPrefix,0,3, inc=1) logger.debug( oneStats ) if len(oneStats) <= 0: isError = True logger.warn( "No active tasks found") result[taskPrefix + 'STATE'] = '1' #return buildNagioOut(errorPrefix + taskPrefix + 'STATE=1 ', result, isError=True) else: errorTasks = 0 for aTask in oneStats.keys(): taskStatus = oneStats[aTask].upper() if taskStatus != 'RUNNING' and taskStatus != 'COMPLETED' and taskStatus != 'ONLINE': errorTasks = errorTasks + 1 #result[taskPrefix + 'STATE'] = taskStatus #return buildNagioOut(errorPrefix + taskPrefix + 'STATE=' + taskStatus + ' ', result, isError=True) if errorTasks <= 0: #result.update(oneStats) result[taskPrefix + 'STATE'] = '0' #taskStatus else: if goodpct < 0 or (((len(oneStats)-errorTasks)/len(oneStats))*100) > goodpct: logger.warn( "More than allowed number of tasks are down: %s out of %s for task: %s" % (errorTasks,len(oneStats),taskPrefix)) result[taskPrefix + 'STATE'] = '2' isError = True result[taskPrefix + 'TOTAL_TASKS'] = str(len(oneStats)-errorTasks) #Get statistics for each Component compErrors = 0 logger.info( "Getting the component statistic list" ) for aSibelComp in components: aComp = compNameMap.get(aSibelComp, aSibelComp) compPrefix = 'comp_'+ aComp + '_' logger.debug( "Getting stat for component: %s" % (aSibelComp) ) child.sendline ('list statistics for component ' + aSibelComp + ' show STAT_ALIAS,SD_DATATYPE,SD_SUBSYSTEM,CURR_VAL,STAT_NAME') child.expect (svrmgr_prompt, timeout=120) stats = child.before oneStats = buildStatDict(stats, compPrefix,0,3) logger.debug( oneStats ) if len(oneStats) <= 0: isError = True compErrors = compErrors + 1 result[compPrefix + '_STATE'] = '1' #return buildNagioOut(errorPrefix + compPrefix + '_STATE=1 ', result, isError=True) else: for aMetric in metrics_scale: metricVal = oneStats.get(aMetric, None) if metricVal != None: metricVal = str(int(float(metricVal)*float(metrics_scale[aMetric]))) oneStats[aMetric] = metricVal result.update(oneStats) logger.info( "All done; exiting!" ) child.sendline ('exit') #time.sleep(1) except Exception: logger.exception("Failed to get statistics") return buildNagioOut(errorPrefix + 'General_Error ', result, isError=True) finally: try: child.close() except Exception: pass if isError: return buildNagioOut(errorPrefix, result, isError=True, isFullMetrics=isFullMetrics) else: return buildNagioOut(successPrefix, result, isError=False, isFullMetrics=isFullMetrics)
import winpexpect as winpexpect winpexpect.run("ssh [email protected] 'mkdir hu'", events={'(?i)password': '******'}) print 'hhhhhhhhhhhhhh' import sys, winpexpect child = winpexpect.winspawn('nslookup') child.logfile = sys.stdout child.expect('\n>') child.sendline('www.google.com') child.expect('\n>') result = winpexpect.winspawn('ssh %s@%s' % ('root', '106.15.224.173')) print result.before, child.after result.sendline('Huqiang2018') result.sendline('ls -l') print result.before, result.after result.interact() print 'hu' result = winpexpect.run("ssh [email protected] 'hostname hu'", events={'(?i)password': '******'}) print 'hu' def test_expect(): ps = winpexpect.winspawn('ping') ps.sendline('exit') print ps.before.decode('gbk')
cmrb = xlrd.open_workbook('c:/python/checkpoint/commands.xls') sheet1 = cmrb.sheet_by_name('commands') num_rows1 = sheet1.nrows num_cols1 = sheet1.ncols ip_addr_list = [sheet.row_values(rawnum)[0] for rawnum in range(sheet.nrows)] commands_list = [sheet1.row_values(rawnum)[0] for rawnum in range(sheet1.nrows)] num_ips = 0 host = '10.10.0.254' user = '******' passwd = '1q2w3e' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) px = winpexpect.winspawn('c:/python/openssh/bin/ssh.exe ' + user + '@' + host) fout = open('c:/python/checkpoint/{0}++.txt'.format(host),"w") px.logfile_read = fout px.timeout = 35 px.expect('authorized use only.') px.sendline(passwd) #create log file with in IP.txt format (10.1.1.1.txt, for example) fout = open('c:/python/checkpoint/{0}++.txt'.format(host),"wb") #push pexpect logfile_read output to log file px.sendline('\n') px.sendline('\n') px.sendline('show interfaces all\n') px.sendline('\n') #for item in ip_addr_list:
from __future__ import unicode_literals import winpexpect import sys child = winpexpect.winspawn('ftp ftp.openbsd.org') child.winpexpect('(?i)name .*: ') child.sendline('anonymous') child.winexpect('(?i)password') child.sendline('*****@*****.**') child.winexpect('ftp> ') child.sendline('bin') child.winexpect('ftp> ') child.sendline('get robots.txt') child.winexpect('ftp> ') sys.stdout.write(child.before) print("Escape character is '^]'.\n") sys.stdout.write(child.after) sys.stdout.flush() child.interact() # Escape character defaults to ^] child.sendline('bye') child.close()
# -*- coding: utf-8 -*- """ @author: Jack L. Clements """ import sys, winpexpect #Note - I wanted to use winpexpect to run a test script that would, similar to a unit test, attempt to test various aspects of this script #Either due to compatability or library issues, winpexpect clearly has other ideas, appending extraneous characters to inputs #It also mangles all non-expect strings into a jumbled half-readable mess #Due to a lack of a linux testing environment at present child = winpexpect.winspawn('Python -u PasswordCheck.py') child.logfile = sys.stdout prompt = 'test' child.expect('Please enter your username: \n') child.sendline( 'User01' ) #appends newline and treats User01, a login attempt, as a whole new child.expect_exact('User01, please enter your old password.') child.expect_exact('Please enter your old password: \n') child.sendline(str('Password1')) child.expect_exact('Please enter a new password: \n') child.sendline(str('TestPass3')) child.expect_exact('Please enter the password again for verification: \n') child.sendline(str('TestPass3')) child.expect_exact('User password changed.') child.close() #code such as this could theoretically be used for unit testing, but I cannot seem to get any implementation to work properly and as such have left it here
from winpexpect import winspawn #ssh = winspawn('ssh',['-tty','[email protected]']) ssh = winspawn('ssh -tt [email protected]') ssh.logfile = sys.stdout i = ssh.expect(['word:'], timeout = 5) print (i) ssh.sendline('xzK3.............')
def executeScript(inputScript, scriptOptionalArgs, inputFile=None): global testcaseInfoList global testcaseInfo global yamlCont testcaseInfoList = [] yamlCont = {} if inputFile != None: fil = open(inputFile, "r") yamlCont = yaml.load(fil) # inputFileType = re.search('(.*).yaml', inputFile).group(1) if re.search("\.log\.", inputScript): cmd = ( "python /work/swtest01_1/sgsubramaniam/sw-test/special_script/demoScript/slowcat.py -d 0.002 %s" % inputScript ) else: cmd = "f10tool %s %s" % (inputScript, " ".join(scriptOptionalArgs)) if re.search("\.flist$", inputScript): inputFileType = "flist" cmd = "f10tool %s %s" % (inputScript, " ".join(scriptOptionalArgs)) elif re.search("\.f10$", inputScript): inputFileType = "f10" cmd = "f10tool %s %s" % (inputScript, " ".join(scriptOptionalArgs)) else: inputFileType = "unknown" if inputFile != None: inputFileType = re.search("(.*).yaml", inputFile).group(1) cmd = "%s %s;echo '----------'" % (inputScript, " ".join(scriptOptionalArgs)) ps = winpexpect.winspawn(cmd) ps.logfile_read = sys.stdout ## Initialize testcaseInfo if the script is not a flist. if inputFileType in ["f10", "unknown"]: scriptName = inputScript testcaseInfo = testInfo(scriptName) testcaseInfoList.append(testcaseInfo) timeout = -1 ps.interact(output_filter=scriptExecutionMonitor) if inputFileType is "flist" or "rspec": ## creates a nested suite suiteList = [] for testcaseInfo in testcaseInfoList: testcaseInfo.flush() suite = createRobotSuite(testcaseInfo) suiteList.append(suite) suite = TestSuite(inputScript) suite.suites = suiteList result = suite.run(output="output.xml", loglevel="debug") for testcaseInfo in testcaseInfoList: testcaseInfo.variableFile.close() else: ## creates a single suite for testcaseInfo in testcaseInfoList: testcaseInfo.flush() print testcaseInfo suite = createRobotSuite(testcaseInfo) result = suite.run(output="output.xml", loglevel="debug") testcaseInfo.variableFile.close() # Generating log files requires processing the earlier generated output XML. ResultWriter("output.xml").write_results() pp = postProcess.postProcess(suiteFile=testcaseInfo.scriptName) pp.close()
def main(): cmdpath = r"C:\Windows\System32\cmd.exe" child = winpexpect.winspawn(cmdpath) child.expect(["C:\Users\cchhsu>"]) child.sendline("Hello World")
def getCustomReport(child, i): iteration = int(i / originalLabelLength) i = i % originalLabelLength #print(iteration, i, originalLabelLength, len(CRValueName)) devRadio = deviceRadio[iteration] s = 'adb -s 192.168.1.31 shell \"dumpsys wifi | grep \'mWifiInfo\'\"' try: if deviceAccess == 'adb': if i == 0: #print("--------- TESTING ------------") child = winpexpect.winspawn( 'adb -s {} shell \"dumpsys wifi | grep \'mWifiInfo:\'\"'. format(deviceIP)) child.expect('Frequency: ', timeout=10) child.expect('\d+') data = child.after #child.sendline('wl -i {} channel'.format(devRadio)) #child.expect('current mac channel') #child.expect('\d+') #data = int(child.after) print('{}: '.format(CRValueName[i]), data) return data elif i == 1: child = winpexpect.winspawn( 'adb -s {} shell \"dumpsys wifi | grep \'mWifiInfo:\'\"'. format(deviceIP)) child.expect('RSSI: ', timeout=10) child.expect('-\d+') data = child.after # child.sendline('wl -i {} bssid'.format(devRadio)) # child.expect('bssid') # child.expect('[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]') # data = (child.after) print('{}: '.format(CRValueName[i]), data) return data elif i == 2: child = winpexpect.winspawn( 'adb -s {} shell \"dumpsys wifi | grep \'mWifiInfo:\'\"'. format(deviceIP)) child.expect('speed: ', timeout=10) child.expect('\d+') data = child.after print('{}: '.format(CRValueName[i]), data) return data elif i == 3: child = winpexpect.winspawn( 'adb -s {} shell \"dumpsys wifi | grep \'mWifiInfo:\'\"'. format(deviceIP)) child.expect('BSSID: ', timeout=10) child.expect( '[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]:[0-9a-fA-F][0-9a-fA-F]' ) data = child.after print('{}: '.format(CRValueName[i]), data) return data elif deviceAccess == 'ssh': if i == 0: child.sendline( 'cd \/System\/Library\/PrivateFrameworks\/Apple80211.framework\/Versions\/Current\/Resources' ) child.expect('$') child.sendline('./airport -I') # was 'wl -i eth2 rssi' child.expect('channel:') child.expect('\d+') data = int(child.after) print('{}: '.format(CRValueName[i]), data) return data elif i == 1: child.sendline('./airport -I') # was 'wl -i eth2 rssi' child.expect('agrCtlRSSI:') child.expect('-\d\d|\d') data = int(child.after) print('{}: '.format(CRValueName[i]), data) return data elif i == 2: child.sendline('./airport -I') # was 'wl -i eth2 rssi' child.expect('lastTxRate:') child.expect('\d+') data = int(child.after) print('{}: '.format(CRValueName[i]), data) return data elif i == 3: child.sendline('./airport -I') # was 'wl -i eth2 rssi' child.expect('MCS:') child.expect('\d+|-\d') data = int(child.after) print('{}: '.format(CRValueName[i]), data) return data return "#N/A" except: print("ERROR - Timeout reached") print("Error on child.before:", child.before, "& child.after:", child.after) data = "#ERROR" print('{}: '.format(CRValueName[i]), data) return data
def test_expect_stderr(self): ps = winspawn('powershell.exe -command -') ps.sendline('Write-Error "my-error"') ps.expect('my-error') ps.terminate()
import sys import winpexpect from pexpect import TIMEOUT from pip._vendor.webencodings.tests import assert_raises ps = winpexpect.winspawn('powershell.exe -command -') assert_raises(TIMEOUT, ps.wait, timeout=2) ps.terminate() child = winpexpect.winspawn('ssh', ['-tty','[email protected]']) child.logfile = sys.stdout child.sendline('Huqiang2018') child .sendline('ls -l /') print('Now enter the FTP interactive mode') child.interact()
def test_timeout(self): ps = winspawn('powershell.exe -command -') ps.sendline('Sleep 10; Write "done sleeping"') assert_raises(TIMEOUT, ps.expect, 'done sleeping', timeout=2) ps.terminate()