RE: pexpect with kadmin

2020-12-23 Thread Joseph L. Casale
> If you have windows 10 can you use Windows Subsystem for Linux  (WSL)
> to install one of the Linux distros and use that?

Interesting idea, sadly I am too far past the deadline on this to go through
the red tape needed to get that in place.

Thanks,
jlc

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pexpect with kadmin

2020-12-23 Thread Barry Scott



> On 23 Dec 2020, at 04:04, Joseph L. Casale  wrote:
> 
> Anyone ever used pexpect with tooling like kadmin and have
> insight into how to manage interacting with it?
> 
> After setting up debug logging, I was able to adjust the expect
> usage to get the input and output logs to at least appear correct
> when setting a password for a principal, however even with a
> successful return code from kadmin, there is some discrepancy
> and the credential is not being set right.
> 
> When run manually, the credentials work fine, it's almost as if
> kadmin is swallowing the newline from pexpect within the password.
> 
> I am using python 3.5 from Windows, over plink.exe, onto a rhel
> 7 server. Unfortunately, I am stuck with all the levels of indirection.

If you have windows 10 can you use Windows Subsystem for Linux  (WSL)
to install one of the Linux distros and use that?

Barry

> 
> Thanks,
> jlc
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

-- 
https://mail.python.org/mailman/listinfo/python-list


pexpect with kadmin

2020-12-22 Thread Joseph L. Casale
Anyone ever used pexpect with tooling like kadmin and have
insight into how to manage interacting with it?

After setting up debug logging, I was able to adjust the expect
usage to get the input and output logs to at least appear correct
when setting a password for a principal, however even with a
successful return code from kadmin, there is some discrepancy
and the credential is not being set right.

When run manually, the credentials work fine, it's almost as if
kadmin is swallowing the newline from pexpect within the password.

I am using python 3.5 from Windows, over plink.exe, onto a rhel
7 server. Unfortunately, I am stuck with all the levels of indirection.

Thanks,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


[issue39404] Pexpect : setwinsize() not working in SLES 12.4 kernel 4.12.14-94.41-default

2020-01-21 Thread Archana Pandey


Change by Archana Pandey :


--
resolution:  -> third party
stage:  -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue39404] Pexpect : setwinsize() not working in SLES 12.4 kernel 4.12.14-94.41-default

2020-01-20 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

The tracker is for issues related to CPython. Can you please add a reproducer 
without pexpect or other dependencies explaining the issue with Python? 
https://github.com/pexpect/pexpect/issues is the issue tracker for pexpect.

--
nosy: +xtreak

___
Python tracker 
<https://bugs.python.org/issue39404>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue39404] Pexpect : setwinsize() not working in SLES 12.4 kernel 4.12.14-94.41-default

2020-01-20 Thread Archana Pandey


New submission from Archana Pandey :

use of setwinsize function returns empty if the values of rows and cols 
differes from(24,80).
Issue occurs only on SLES 12.4.

sample code:
#!/usr/bin/env python
from pexpect import pxssh
try:
s = pxssh.pxssh()
hostname = 'someIp'
username = 'username'
password = 'password'
s.login(hostname, username, password)
s.setwinsize(1000,1000)  # setting default winsize works
s.sendline('uname -r')   # run a command
s.prompt() # match the prompt
print(s.before)# print everything before the prompt.
s.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)

--
components: Library (Lib)
messages: 360356
nosy: archi-pandey
priority: normal
severity: normal
status: open
title: Pexpect : setwinsize() not working in SLES 12.4 kernel 
4.12.14-94.41-default
type: behavior
versions: Python 3.6

___
Python tracker 
<https://bugs.python.org/issue39404>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: Pexpect

2017-01-07 Thread alister
On Fri, 06 Jan 2017 12:00:32 +1200, Iranna Mathapati wrote:

> Hi Team,
> 
> How to match latter(caps and small) ,numbers and # symbol in python
> pexpect.
> 
> 
> Thanks,
> Iranna M

Simple
just write a small program
 



-- 
New screensaver released: Curtains for Windows.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect

2017-01-06 Thread Cameron Simpson

On 06Jan2017 11:37, Joaquin Alzola <joaquin.alz...@lebara.com> wrote:

Iranna Mathapati <iranna.gan...@gmail.com> asked:

How to match latter(caps and small) ,numbers and # symbol in python pexpect.


With a .*


Ugh. Please not. Expect() accepts a nongreedy regular expression. ".*" is the 
lazy "match absolutely anything" pattern. Generally overused and imprecise.  
Iranna Mathapati knows what to look for.


See the documentation for the re module, specificly the regular expression 
syntax:


 https://docs.python.org/3/library/re.html#regular-expression-syntax

To match letters, digits and "#", try:

 [0-9a-zA-Z#]*

Cheers,
Cameron Simpson <c...@zip.com.au>
--
https://mail.python.org/mailman/listinfo/python-list


Pexpect

2017-01-06 Thread Iranna Mathapati
Hi Team,

How to match latter(caps and small) ,numbers and # symbol in python pexpect.


Thanks,
Iranna M

-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Pexpect

2017-01-06 Thread Joaquin Alzola
> How to match latter(caps and small) ,numbers and # symbol in python pexpect.

With a .*

child = pexpect.spawnu("ssh cbpapp@%s"% CBP[cust_cbp_server])
child.setecho(False)
child.logfile = open("/opt/webapi/logs/delete_accountID.log", "w")
child.expect(".*assword:")
child.sendline("\r")
child.expect(".*/onip/app/cbpapp>")
child.sendline("mdsql\r")
child.expect("SQL>")
child.sendline("select * from table; \r")
child.expect("SQL>")
child.expect("SQL>")

-

This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
-- 
https://mail.python.org/mailman/listinfo/python-list


Pexpect

2017-01-06 Thread Iranna Mathapati
Hi Team,

How to match latter(caps and small) ,numbers and # symbol in python pexpect.


Thanks,
Iranna M
-- 
https://mail.python.org/mailman/listinfo/python-list


Pexpect

2016-12-10 Thread Iranna Mathapati
Hi Team,



The fallowing script(function) is working if its in PDB mode(trace line by
line) but same script is not working if its remove/comment PDB and run one
shot.



log.info("Time out expection")

uut_con1 = pexpect.spawn('telnet %s'%power_ip)

uut_con1.logfile = sys.stdout

uut_con1.delaybeforesend = None

time.sleep(30)

uut_con1.send("%s\r" % username)

uut_con1.expect([r"Password:"],timeout=30)

uut_con1.send("%s\r" % pass_word)

time.sleep(30)

uut_con1.send("\r")

uut_con1.expect([r'#?'],timeout=30)

uut_con1.send("power outlets %d off\r"%outlet)

uut_con1.expect([r'wish to turn outlet'],timeout=30)

uut_con1.send("y\r")

uut_con1.send("\r")

uut_con1.expect([r'#?'],timeout=30)

uut_con1.send("power outlets %d on\r"%outlet)

uut_con1.expect([r'wish to turn outlet'],timeout=30)

uut_con1.send("y\r")

uut_con1.send("\r")

uut_con1.expect([r'#?'],timeout=30)

uut_con1.close()

uut_con.close()

time.sleep(300)


check_prompt(self,username,pass_word,dev_ip,dev_port,power_ip,outlet)



*I got fallowing error:*



2016-12-10T02:24:42: %aetest-INFO: Time out expection

Trying 172.31.206.143...

Connected to 172.31.206.143.

Escape character is '^]'.

Login for PX2 CLI

Username: admin

power outlets 21 off



Welcome to PX2 CLI!

Last login: 2001-06-30 11:53:59 EDT [CLI (Telnet) from 172.31.144.6]



#

# power outlets 21 off



yower outlets 21 on outlet 21 off? [y/n] y



power outlets 21 on

# 2016-12-10T02:26:12: %aetest-ERROR: Caught exception during execution:

2016-12-10T02:26:13: %aetest-ERROR: Traceback (most recent call last):

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/rajtamil/pyATS2.7/hlite/eor/systest/scripts/NAT/ATS_CLEAN_N9K.py",
line 354, in connect_devices

2016-12-10T02:26:13: %aetest-ERROR:
check_prompt(self,username,pass_word,dev_ip,dev_port,power_ip,outlet)

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/rajtamil/pyATS2.7/hlite/eor/systest/scripts/NAT/ATS_CLEAN_N9K.py",
line 282, in check_prompt

2016-12-10T02:26:13: %aetest-ERROR: uut_con1.expect([r'wish to turn
outlet'],timeout=30)

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/svanalin/pyats2/lib/python2.7/site-packages/pexpect/spawnbase.py",
line 321, in expect

2016-12-10T02:26:13: %aetest-ERROR: timeout, searchwindowsize, async)

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/svanalin/pyats2/lib/python2.7/site-packages/pexpect/spawnbase.py",
line 345, in expect_list

2016-12-10T02:26:13: %aetest-ERROR: return exp.expect_loop(timeout)

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/svanalin/pyats2/lib/python2.7/site-packages/pexpect/expect.py",
line 107, in expect_loop

2016-12-10T02:26:13: %aetest-ERROR: return self.timeout(e)

2016-12-10T02:26:13: %aetest-ERROR:   File
"/auto/n3k-qa/CODC/svanalin/pyats2/lib/python2.7/site-packages/pexpect/expect.py",
line 70, in timeout

2016-12-10T02:26:13: %aetest-ERROR: raise TIMEOUT(msg)

2016-12-10T02:26:13: %aetest-ERROR: TIMEOUT: Timeout exceeded.

2016-12-10T02:26:13: %aetest-ERROR: 

2016-12-10T02:26:13: %aetest-ERROR: command: /usr/bin/telnet

2016-12-10T02:26:13: %aetest-ERROR: args: ['/usr/bin/telnet',
'172.31.206.143']

2016-12-10T02:26:13: %aetest-ERROR: buffer (last 100 chars): ' 21 off?
[y/n] y\r\n\r\npower outlets 21 on\r\n# '

2016-12-10T02:26:13: %aetest-ERROR: before (last 100 chars): ' 21 off?
[y/n] y\r\n\r\npower outlets 21 on\r\n# '

2016-12-10T02:26:13: %aetest-ERROR: after: 

2016-12-10T02:26:13: %aetest-ERROR: match: None

2016-12-10T02:26:13: %aetest-ERROR: match_index: None

2016-12-10T02:26:13: %aetest-ERROR: exitstatus: None

2016-12-10T02:26:13: %aetest-ERROR: flag_eof: False

2016-12-10T02:26:13: %aetest-ERROR: pid: 9163

2016-12-10T02:26:13: %aetest-ERROR: child_fd: 18

2016-12-10T02:26:13: %aetest-ERROR: closed: False

2016-12-10T02:26:13: %aetest-ERROR: timeout: 30

2016-12-10T02:26:13: %aetest-ERROR: delimiter: 

2016-12-10T02:26:13: %aetest-ERROR: logfile: ', mode
'w' at 0xf7712078>

2016-12-10T02:26:13: %aetest-ERROR: logfile_read: None

2016-12-10T02:26:13: %aetest-ERROR: logfile_send: None

2016-12-10T02:26:13: %aetest-ERROR: maxread: 2000

2016-12-10T02:26:13: %aetest-ERROR: ignorecase: False

2016-12-10T02:26:13: %aetest-ERROR: searchwindowsize: None

2016-12-10T02:26:13: %aetest-ERROR: delaybeforesend: None

2016-12-10T02:26:13: %aetest-ERROR: delayafterclose: 0.1

2016-12-10T02:26:13: %aetest-ERROR: delayafterterminate: 0.1

2016-12-10T02:26:13: %aetest-ERROR: searcher: searcher_re:

2016-12-10T02:26:

pexpect matching?

2015-11-16 Thread Didymus
Greetings,

  I have the following code:

import pexpect

child = pexpect.spawn('/bin/bash')
i = child.expect_exact('bash-3.2$ ')

child.sendline("rpm -q --queryformat '%{VERSION}\\n' glibc")
i = child.expect (['2', '2.5', '2.52.5', pexpect.TIMEOUT])

print  child.before
print '---'
print  child.after

if i == 0:
print 'We got 2'
elif i == 1:
print 'We got 2.5'
elif i == 2:
print ' We got 7'
elif i == 3:
print 'Timed Out!'
else:
print 'What happened?'

The output of the commandline is:

% rpm -q --queryformat '%{VERSION}\n' glibc
2.5
2.5


I've tried to use "\b", "^", "$" around the return stings and even 
expect_exact, but end up with it printing "We got 2". It's just mathcing the 
first character and not the entire string.

rpm -q --queryformat '%{VERSION}\n' glibc

---
2
We got 2

What am I doing wrong here? What do I need to tell the expect line  to grab the 
entire line back to check against?

Thanks
  Tom
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help in pexpect multiprocessing

2015-11-16 Thread harirammanohar159
On Monday, 9 November 2015 18:07:36 UTC+5:30, hariramm...@gmail.com  wrote:
> Hi,
> 
> I am using multiprocessing with pexpect, issue is whenever i call a function 
> which is having expect(), its throwing error which is genuine as multiple 
> threads are processing it same time (i/o prompt same time by multiple 
> processes..so issues in picture...), so i want to use lock for that section 
> alone to avoid it, but still fails in implementing it...can you help me
> 
> username = input('Enter your username: ')
> password = getpass.getpass()
> 
> s = pxssh.pxssh()
> s.login ('host','username','password')
> s.sendline ('ps -ef|grep java')
> s.prompt(timeout=1)
> 
> Try 1:
> 
> if condition == 'met':
>np = len(list1)
>p = multiprocessing.Pool(np)
>p.map(stop, [(ds) for ds in list1])
> 
> def stop(ds):
> s.sendline ('cd /usr')
> if condition:
> lock = threading.Lock()
> lock.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> lock.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Try 2:
> 
> if condition == 'met':
> lock = Lock()
> for ds in list1:
> Process(target=stop, args=(ds,lock)).start()
> 
> def stop(ds,l):
> s.sendline ('cd /usr')
> if condition:
> l.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> l.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Both are giving me same trace..
> 
> pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" 
> is 0, but there was no child process. Did someone else call waitpid() on our 
> process?
> 
> Thanks in Advance

Hey Lucena,

Thank you for suggestion, yeah process queues doing the samething, creating new 
sesssion for each process and executing simulatenously.. requirement is served..

but still i want to tackle the situation with locks, but not able to as 
throwing the below error.

pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" is 
0, but there was no child process. Did someone else call waitpid() on our 
process? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help in pexpect multiprocessing

2015-11-10 Thread harirammanohar159
On Monday, 9 November 2015 18:07:36 UTC+5:30, hariramm...@gmail.com  wrote:
> Hi,
> 
> I am using multiprocessing with pexpect, issue is whenever i call a function 
> which is having expect(), its throwing error which is genuine as multiple 
> threads are processing it same time (i/o prompt same time by multiple 
> processes..so issues in picture...), so i want to use lock for that section 
> alone to avoid it, but still fails in implementing it...can you help me
> 
> username = input('Enter your username: ')
> password = getpass.getpass()
> 
> s = pxssh.pxssh()
> s.login ('host','username','password')
> s.sendline ('ps -ef|grep java')
> s.prompt(timeout=1)
> 
> Try 1:
> 
> if condition == 'met':
>np = len(list1)
>p = multiprocessing.Pool(np)
>p.map(stop, [(ds) for ds in list1])
> 
> def stop(ds):
> s.sendline ('cd /usr')
> if condition:
> lock = threading.Lock()
> lock.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> lock.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Try 2:
> 
> if condition == 'met':
> lock = Lock()
> for ds in list1:
> Process(target=stop, args=(ds,lock)).start()
> 
> def stop(ds,l):
> s.sendline ('cd /usr')
> if condition:
> l.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> l.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Both are giving me same trace..
> 
> pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" 
> is 0, but there was no child process. Did someone else call waitpid() on our 
> process?
> 
> Thanks in Advance

Hi,

can any one check it out
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help in pexpect multiprocessing

2015-11-10 Thread harirammanohar159
On Monday, 9 November 2015 18:07:36 UTC+5:30, hariramm...@gmail.com  wrote:
> Hi,
> 
> I am using multiprocessing with pexpect, issue is whenever i call a function 
> which is having expect(), its throwing error which is genuine as multiple 
> threads are processing it same time (i/o prompt same time by multiple 
> processes..so issues in picture...), so i want to use lock for that section 
> alone to avoid it, but still fails in implementing it...can you help me
> 
> username = input('Enter your username: ')
> password = getpass.getpass()
> 
> s = pxssh.pxssh()
> s.login ('host','username','password')
> s.sendline ('ps -ef|grep java')
> s.prompt(timeout=1)
> 
> Try 1:
> 
> if condition == 'met':
>np = len(list1)
>p = multiprocessing.Pool(np)
>p.map(stop, [(ds) for ds in list1])
> 
> def stop(ds):
> s.sendline ('cd /usr')
> if condition:
> lock = threading.Lock()
> lock.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> lock.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Try 2:
> 
> if condition == 'met':
> lock = Lock()
> for ds in list1:
> Process(target=stop, args=(ds,lock)).start()
> 
> def stop(ds,l):
> s.sendline ('cd /usr')
> if condition:
> l.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> l.release()
> s.prompt(timeout=200)
> print('stopped ds...')
> 
> Both are giving me same trace..
> 
> pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" 
> is 0, but there was no child process. Did someone else call waitpid() on our 
> process?
> 
> Thanks in Advance

Hi,

I am able to manage it by using process queues, thank you
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help in pexpect multiprocessing

2015-11-10 Thread Pablo Lucena
I think the problem is that you cannot pass around an open socket via
pickle. Whats the error message you are getting?

Try adding the session establishment code to the stop function, so that
each new process opens a session to the server and executes the command.

def stop(ds):
s = pxssh.pxssh()
​​
s.login ('host','username','password')
s.sendline ('ps -ef|grep java')
s.prompt(timeout=1)
s.sendline ('cd /usr')
if condition:
lock = threading.Lock()
lock.acquire()
s.expect('Enter username:')
s.sendline ('user')
s.expect('Enter password:*')
s.sendline('pass')
lock.release()
s.prompt(timeout=200)
print('stopped ds...')


if condition == 'met':
   np = len(list1)
   p = multiprocessing.Pool(np)
   p.map(stop, [(ds) for ds in list1])

On Mon, Nov 9, 2015 at 7:37 AM, <harirammanohar...@gmail.com> wrote:

> Hi,
>
> I am using multiprocessing with pexpect, issue is whenever i call a
> function which is having expect(), its throwing error which is genuine as
> multiple threads are processing it same time (i/o prompt same time by
> multiple processes..so issues in picture...), so i want to use lock for
> that section alone to avoid it, but still fails in implementing it...can
> you help me
>
> username = input('Enter your username: ')
> password = getpass.getpass()
>
> s = pxssh.pxssh()
> s.login ('host','username','password')
> s.sendline ('ps -ef|grep java')
> s.prompt(timeout=1)
>
> Try 1:
>
> if condition == 'met':
>np = len(list1)
>p = multiprocessing.Pool(np)
>p.map(stop, [(ds) for ds in list1])
>
> def stop(ds):
> s.sendline ('cd /usr')
> if condition:
> lock = threading.Lock()
> lock.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> lock.release()
> s.prompt(timeout=200)
> print('stopped ds...')
>
> Try 2:
>
> if condition == 'met':
> lock = Lock()
> for ds in list1:
> Process(target=stop, args=(ds,lock)).start()
>
> def stop(ds,l):
> s.sendline ('cd /usr')
> if condition:
> l.acquire()
> s.expect('Enter username:')
> s.sendline ('user')
> s.expect('Enter password:*')
> s.sendline('pass')
> l.release()
> s.prompt(timeout=200)
> print('stopped ds...')
>
> Both are giving me same trace..
>
> pexpect.ExceptionPexpect: isalive() encountered condition where
> "terminated" is 0, but there was no child process. Did someone else call
> waitpid() on our process?
>
> Thanks in Advance
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
*Pablo Lucena*
-- 
https://mail.python.org/mailman/listinfo/python-list


help in pexpect multiprocessing

2015-11-09 Thread harirammanohar159
Hi,

I am using multiprocessing with pexpect, issue is whenever i call a function 
which is having expect(), its throwing error which is genuine as multiple 
threads are processing it same time (i/o prompt same time by multiple 
processes..so issues in picture...), so i want to use lock for that section 
alone to avoid it, but still fails in implementing it...can you help me

username = input('Enter your username: ')
password = getpass.getpass()

s = pxssh.pxssh()
s.login ('host','username','password')
s.sendline ('ps -ef|grep java')
s.prompt(timeout=1)

Try 1:

if condition == 'met':
   np = len(list1)
   p = multiprocessing.Pool(np)
   p.map(stop, [(ds) for ds in list1])

def stop(ds):
s.sendline ('cd /usr')
if condition:
lock = threading.Lock()
lock.acquire()
s.expect('Enter username:')
s.sendline ('user')
s.expect('Enter password:*')
s.sendline('pass')
lock.release()
s.prompt(timeout=200)
print('stopped ds...')

Try 2:

if condition == 'met':
lock = Lock()
for ds in list1:
Process(target=stop, args=(ds,lock)).start()

def stop(ds,l):
s.sendline ('cd /usr')
if condition:
l.acquire()
s.expect('Enter username:')
s.sendline ('user')
s.expect('Enter password:*')
s.sendline('pass')
l.release()
s.prompt(timeout=200)
print('stopped ds...')

Both are giving me same trace..

pexpect.ExceptionPexpect: isalive() encountered condition where "terminated" is 
0, but there was no child process. Did someone else call waitpid() on our 
process?

Thanks in Advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-10 Thread harirammanohar159
Hey,

its resolved by small tweak :)
do child.sendline('logout') instead of child.logout()

Thanks...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread harirammanohar159
On Tuesday, 8 September 2015 17:07:24 UTC+5:30, hariramm...@gmail.com  wrote:
> Some where i am missing simple logic :)
> 
> =
> child = pexpect.spawn('ssh hari@hostname')
> child.logfile = sys.stdout
> child.expect('hari\'s Password: ')
> =
> 
> getting error as follows:
> 
> child.expect('hari\'s Password: ')
> TypeError: must be str, not bytes
> ===
> 
> Thanks...

Hey All,

I am able to achieve this using pxssh.. thank you for help...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread harirammanohar159
On Tuesday, 8 September 2015 17:07:24 UTC+5:30, hariramm...@gmail.com  wrote:
> Some where i am missing simple logic :)
> 
> =
> child = pexpect.spawn('ssh hari@hostname')
> child.logfile = sys.stdout
> child.expect('hari\'s Password: ')
> =
> 
> getting error as follows:
> 
> child.expect('hari\'s Password: ')
> TypeError: must be str, not bytes
> ===
> 
> Thanks...

Hey Laura,

spawnu worked for handling the unicode, thank you for that, yes i have already 
tried paramiko, it didnt worked for the same purpose (tried both sftp client 
and ssh client of paramiko module; finally while doing su getting the error as 
expecting tty terminal...)

fabric will work but it is up to only python 2.7

so just i am trying to work out with pexpect whether it will be of any use or 
not.

(my goal is to login to remote server then do su then execute commands...)

Thank you for spawnu, now i got stuck with freezing issue similar to it is not 
returing to the shell prompt...its on waiting...i had to press ctrl+c

===
child.sendline(password)
child.expect('-bash-4.1$')
child.sendline('ls')
print(child.before)
child.sendline('su - user1')
child.expect('-bash-4.1$')
child.sendline('pwd; hostname')
print(child.before)
child.close()
=
output:


hari's Password: 
ls

WARNING. You have accessed a private computer system.
Unauthorized access,use,connection,or entry is not permitted
and constitutes a crime punishable by law. We reserve the
right to fully pursue criminal and civil legal penalties.
All individuals using this computer system with or without proper
authority are subject to having all their activities monitored
and recorded. Anyone using this system implicitly consents to
this monitoring. Any evidence of suspected criminal activity
revealed by such monitoring may be provided to law enforcement officials.


su - user1

lsTotal users logged in under your name (via BoKS): 3 (2 on this host)
Total users logged in (via BoKS): 8324 (2 on this host)



#
#   For Authorized Use Only #
#   #
#   Activities on this system are subject to being monitored#
#   or recorded for all users, authorized or unauthorized.  #
#   Use of the system is considered consent to such monitoring. #
#   Any evidence of possible criminal activity may be provided  #
#   to law enforcement. #
#   #
#



-bash-4.1$ ls
-bash-4.1$ su - user1
-bash-4.1$


^CTraceback (most recent call last):
  File "./rmcomments.py", line 16, in 
child.expect('-bash-4.1$')
  File 
"/ceopt/utils/python/3.4.3/custommodules/lib/python3.4/site-packages/pexpect/__init__.py",
 line 1451, in expect
timeout, searchwindowsize)
  File 
"/ceopt/utils/python/3.4.3/custommodules/lib/python3.4/site-packages/pexpect/__init__.py",
 line 1466, in expect_list
timeout, searchwindowsize)
  File 
"/ceopt/utils/python/3.4.3/custommodules/lib/python3.4/site-packages/pexpect/__init__.py",
 line 1535, in expect_loop
c = self.read_nonblocking(self.maxread, timeout)
  File 
"/ceopt/utils/python/3.4.3/custommodules/lib/python3.4/site-packages/pexpect/__init__.py",
 line 958, in read_nonblocking
r, w, e = self.__select([self.child_fd], [], [], timeout)
  File 
"/ceopt/utils/python/3.4.3/custommodules/lib/python3.4/site-packages/pexpect/__init__.py",
 line 1717, in __select
return select.select(iwtd, owtd, ewtd, timeout)
KeyboardInterrupt



-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread Laura Creighton
>Hey All,
>
>I am able to achieve this using pxssh.. thank you for help...

Great to hear it.  Good luck with the crazies.
Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread harirammanohar159
On Tuesday, 8 September 2015 17:07:24 UTC+5:30, hariramm...@gmail.com  wrote:
> Some where i am missing simple logic :)
> 
> =
> child = pexpect.spawn('ssh hari@hostname')
> child.logfile = sys.stdout
> child.expect('hari\'s Password: ')
> =
> 
> getting error as follows:
> 
> child.expect('hari\'s Password: ')
> TypeError: must be str, not bytes
> ===
> 
> Thanks...

Hi Laura,

Basically its the same, no difference if i keep su user1...
i am getting the desired output with a single host, but if i keep for loop for 
multiple hosts, remaining are skipped saying as below:

pexpect.TIMEOUT: Timeout exceeded.

During handling of the above exception, another exception occurred:

pexpect.TIMEOUT: Timeout exceeded.


only 1st host is getting executed. how to control child.logout() and make for 
loop continue...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread Laura Creighton
In a message of Wed, 09 Sep 2015 01:58:30 -0700, harirammanohar...@gmail.com wr
ites:

>Thank you for spawnu, now i got stuck with freezing issue similar to it is not 
>returing to the shell prompt...its on waiting...i had to press ctrl+c
>
>===
>child.sendline(password)
>child.expect('-bash-4.1$')
>child.sendline('ls')
>print(child.before)
>child.sendline('su - user1')
>child.expect('-bash-4.1$')
>child.sendline('pwd; hostname')
>print(child.before)
>child.close()

>WARNING. You have accessed a private computer system.


Any doubts we had about whether the computer policy authorities
as this place are 'nuttier than 2 trees full of squirrels' are
now put to rest.  I just hope I am not helping you do things that
is going to end up with them trying to put you in jail.  Poor you.

>su - user1
>
>lsTotal users logged in under your name (via BoKS): 3 (2 on this host)
>Total users logged in (via BoKS): 8324 (2 on this host)
>-bash-4.1$ ls
>-bash-4.1$ su - user1
>-bash-4.1$

Okay.
Instead of waiting for that bash-4.1 prompt
after you issue your su, issue whoami
and wait to see if it returns user1.

That way we can see if the problem is with expect waiting for the prompt
which for some reason it is not seeing, or whether it is just lost, lost,
lost.

Also, for informational purposes try your su without the '-'
just "su user1", and see if it is some part of the 'provide an environment
similar to what the user would get if the user logged in directly'
ability of su that is confusing things.

Laura


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-09 Thread harirammanohar159
On Tuesday, 8 September 2015 17:07:24 UTC+5:30, hariramm...@gmail.com  wrote:
> Some where i am missing simple logic :)
> 
> =
> child = pexpect.spawn('ssh hari@hostname')
> child.logfile = sys.stdout
> child.expect('hari\'s Password: ')
> =
> 
> getting error as follows:
> 
> child.expect('hari\'s Password: ')
> TypeError: must be str, not bytes
> ===
> 
> Thanks...

Hi,

can you check it and let me know the way...

Thanks...
-- 
https://mail.python.org/mailman/listinfo/python-list


issue while doing pexpect ssh

2015-09-08 Thread harirammanohar159
Some where i am missing simple logic :)

=
child = pexpect.spawn('ssh hari@hostname')
child.logfile = sys.stdout
child.expect('hari\'s Password: ')
=

getting error as follows:

child.expect('hari\'s Password: ')
TypeError: must be str, not bytes
===

Thanks...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-08 Thread Laura Creighton
In a message of Tue, 08 Sep 2015 04:37:09 -0700, harirammanohar...@gmail.com wr
ites:
>Some where i am missing simple logic :)
>
>=
>child = pexpect.spawn('ssh hari@hostname')
>child.logfile = sys.stdout
>child.expect('hari\'s Password: ')
>=
>
>getting error as follows:
>
>child.expect('hari\'s Password: ')
>TypeError: must be str, not bytes
>===
>
>Thanks...
>-- 
>https://mail.python.org/mailman/listinfo/python-list

https://pexpect.readthedocs.org/en/latest/api/pexpect.html#run-function
you want to use spawnu because you have a unicode string.

Laura
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-08 Thread Chris Angelico
On Tue, Sep 8, 2015 at 9:37 PM,   wrote:
> Some where i am missing simple logic :)
>
> =
> child = pexpect.spawn('ssh hari@hostname')
> child.logfile = sys.stdout
> child.expect('hari\'s Password: ')
> =
>
> getting error as follows:
> 
> child.expect('hari\'s Password: ')
> TypeError: must be str, not bytes
> ===

Laura's already answered your actual question. But I would recommend
using public key login rather than keying in a password; it's a lot
more secure, as it means you don't have to embed a password in your
source code (or at very best, on your hard disk in some other readable
and decryptable way). It also simplifies the transaction
significantly.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-08 Thread Laura Creighton
In a message of Tue, 08 Sep 2015 23:57:41 +1000, Chris Angelico writes:
>On Tue, Sep 8, 2015 at 9:37 PM,   wrote:
>> Some where i am missing simple logic :)
>>
>> =
>> child = pexpect.spawn('ssh hari@hostname')
>> child.logfile = sys.stdout
>> child.expect('hari\'s Password: ')
>> =
>>
>> getting error as follows:
>> 
>> child.expect('hari\'s Password: ')
>> TypeError: must be str, not bytes
>> ===
>
>Laura's already answered your actual question. But I would recommend
>using public key login rather than keying in a password; it's a lot
>more secure, as it means you don't have to embed a password in your
>source code (or at very best, on your hard disk in some other readable
>and decryptable way). It also simplifies the transaction
>significantly.
>
>ChrisA

This poor soul cannot login at all. He needs this hack to let him
su some-other-user because of a draconian policy he cannot do
anything about.  If he could just log in, one heck of a lot of
other things would be simpler for him ...

Laura

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: issue while doing pexpect ssh

2015-09-08 Thread jmp

On 09/08/2015 03:57 PM, Chris Angelico wrote:

On Tue, Sep 8, 2015 at 9:37 PM,   wrote:

Some where i am missing simple logic :)

=
child = pexpect.spawn('ssh hari@hostname')
child.logfile = sys.stdout
child.expect('hari\'s Password: ')
=

getting error as follows:

child.expect('hari\'s Password: ')
TypeError: must be str, not bytes
===


Laura's already answered your actual question. But I would recommend
using public key login [snip]

ChrisA



My 2 cents, beside the public key, use the python module paramiko, 
unless you really want to work at the low level yourself.


http://docs.paramiko.org/en/1.15/api/client.html

JM

--
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-15 Thread Thomas 'PointedEars' Lahn
Skip Montanaro wrote:

 That might have to do with
 http://www.catb.org/~esr/faqs/smart-questions.html, specifically
 http://www.catb.org/~esr/faqs/smart-questions.html#prune.
 
 Thanks, but not really helpful. I'm well aware of Eric Raymond's
 contributions to the open source world. I'm also aware aware that my
 question was not perfectly well-formed.

It was really helpful, you just do not realize it yet.

F'up2 poster

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-14 Thread Skip Montanaro
 Will I be in over my head trying to tweak the output? Hmmm... maybe if I
tell top TERM=dumb?

 You may need to tell it TERM=dumb, though it might also refuse to run.

It does run w/ TERM=dumb, so hopefully I won't have to resort to defining
my own terminal definition. (Now, *that* takes me back.) Now to see how
simple the output is...

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-14 Thread Thomas 'PointedEars' Lahn
Skip Montanaro wrote:

 Let's just let this thread die, shall we? So far, nobody seems interested
 in attempting to answer my original question.

That might have to do with
http://www.catb.org/~esr/faqs/smart-questions.html, specifically
http://www.catb.org/~esr/faqs/smart-questions.html#prune.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-14 Thread Cameron Simpson

On 13Mar2015 10:17, Skip Montanaro skip.montan...@gmail.com wrote:

I have this tweak I'd like to make to the top command (Linux only is fine).
[...] However... I have a feeling I might be fairly seriously
challenged trying to work with top's raw output, as it probably does
something more sophisticated than clear the screen and spit out rows. Will
I be in over my head trying to tweak the output? Hmmm... maybe if I tell
top TERM=dumb?


You may need to tell it TERM=dumb, though it might also refuse to run.

Like many full screen terminal apps, top is built on top of curses or ncurses; 
these libraries try to do minimal tty output, so they maintain an in memory 
image of the screen and only emit the terminal sequences requires to update 
changes. Much escape sequence parsing etc if you want to hack their output.


Now, if TERM-dumb is a no-go with top, another alternative is to write your own 
terminal definition (not trivial, but not too hard either as you don't need to 
implement all the operations, or even many of them: curses, given _sufficient_ 
capabilities, will figure it out). You might write an easy to parse terminal 
definition and run your own parser, and have _it_ output to python curses (with 
the correct $TERM on the output side).


But I suspect it might be just as easy to implement your own top by parsing 
stuff from /proc.


Your call...

Cheers,
Cameron Simpson c...@zip.com.au
--
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-14 Thread Skip Montanaro
 That might have to do with
 http://www.catb.org/~esr/faqs/smart-questions.html, specifically
 http://www.catb.org/~esr/faqs/smart-questions.html#prune.

Thanks, but not really helpful. I'm well aware of Eric Raymond's
contributions to the open source world. I'm also aware aware that my
question was not perfectly well-formed.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Thomas 'PointedEars' Lahn
Skip Montanaro wrote:

 Thomas 'PointedEars' Lahn […] wrote:
 Yes, it (top(1) from procps-ng 3.3.9) does.  Either run

   top -u '!root'

 or type “o” (for case-insensitive filter), then e.g. “!USER=root” to show
 processes started by all users except “root”.  RTFM.
 
 Neither works on what I have available at work (OpenSuSE 12.2). -u only
 accepts a single user name or id in my world. -o doesn't exist at all.

“o” is not an option, it is an interaktive keystroke command in (my) top(1).  
Press “h” for help (I found out this way while reading your posting).

OpenSUSE 12.2 has procps 3.3.3 which does not support “-u '!$USER'” yet; 
however, OpenSUSE 12.2 has reached its end-of-life on 2014-01-27.

 Thanks for the pointer though.

You’re welcome.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Skip Montanaro
On Fri, Mar 13, 2015 at 12:03 PM, Thomas 'PointedEars' Lahn
pointede...@web.de wrote:
 “o” is not an option, it is an interaktive keystroke command in (my) top(1).

o is also an unrecognized keystroke.

 OpenSUSE 12.2 has reached its end-of-life on 2014-01-27.

I understand that. Tell that to management though. They were working
on 13.1 for awhile, but seem to be focused on 13.2 now, though not all
our internal software works on that.

I'll give up on hoping I get access to a more modern top anytime soon.
Can someone give me some feedback on my harebrained pexpect idea?

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Skip Montanaro
On Fri, Mar 13, 2015 at 5:47 PM, Christian Gollwitzer aurio...@gmx.de
wrote:

 Why? Do you not have a C compiler?


Sure I do, and I'm not afraid to use it. I realize top is just one
not-terribly-critical tool, but every divergence between my machines and
the standard install just makes it that much more difficult for me to
track changes when our IT group *does* move us to a more up-to-date
environment. I develop and build software which runs in a production
environment. I can't afford to diverge more than absolutely necessary.

Let's just let this thread die, shall we? So far, nobody seems interested
in attempting to answer my original question. I thought it might be an
interesting hack if I could make it work. If I plunge in and try it, I will
report back with results.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Christian Gollwitzer
Am 13.03.15 um 18:25 schrieb Skip Montanaro:
 I understand that. Tell that to management though. They were working
 on 13.1 for awhile, but seem to be focused on 13.2 now, though not all
 our internal software works on that.
 
 I'll give up on hoping I get access to a more modern top anytime soon.

Why? Do you not have a C compiler?

Christian

-- 
https://mail.python.org/mailman/listinfo/python-list


Pexpect idea - but can I handle curses?

2015-03-13 Thread Skip Montanaro
I have this tweak I'd like to make to the top command (Linux only is fine).
Most of the time I want to see just one user or all users. Every now and
again though, I'd like to see all users except another.  Top doesn't
support this functionality, but I thought something like -u -root would
be a handy extension. Another would be to watch multiple users, e.g. -u
skip,bob. I thought I could fire up a top command showing all users in a
pseudo tty with a fake huge number of lines, then elide the rows matching
unwanted users. However... I have a feeling I might be fairly seriously
challenged trying to work with top's raw output, as it probably does
something more sophisticated than clear the screen and spit out rows. Will
I be in over my head trying to tweak the output? Hmmm... maybe if I tell
top TERM=dumb?

Anyway, before I get in over my head on the input side, I thought I would
check to see if I'm likely to hit a brick wall on the output side...

Thx,

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Skip Montanaro
On Fri, Mar 13, 2015 at 10:54 AM, Thomas 'PointedEars' Lahn 
pointede...@web.de wrote:

 Yes, it (top(1) from procps-ng 3.3.9) does.  Either run

   top -u '!root'

 or type “o” (for case-insensitive filter), then e.g. “!USER=root” to show
 processes started by all users except “root”.  RTFM.


Neither works on what I have available at work (OpenSuSE 12.2). -u only
accepts a single user name or id in my world. -o doesn't exist at all.

Thanks for the pointer though.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pexpect idea - but can I handle curses?

2015-03-13 Thread Thomas 'PointedEars' Lahn
Skip Montanaro wrote:

 I have this tweak I'd like to make to the top command (Linux only is
 fine). Most of the time I want to see just one user or all users. Every
 now and again though, I'd like to see all users except another.  Top 
 doesn't support this functionality,

Yes, it (top(1) from procps-ng 3.3.9) does.  Either run

  top -u '!root'

or type “o” (for case-insensitive filter), then e.g. “!USER=root” to show 
processes started by all users except “root”.  RTFM.

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Why captured match is displayed as part of pexpect .after ?

2014-09-13 Thread Viet Nguyen
Hi,

If any is familiar with pexpect, please help to point out why my script seems 
to fail to capture the desired text.

Here, I want to log into a server 172.27.161.19.  Once I see Username: , I 
will type in my userid admin.

The problem here is I have a list of keywords for pexpect to match before 
returning the matched item for me.  The list consists of following list items:

expects = ['yes', '.*Username: ', '.*login: |.*Login: ', 'SY-FAR-1', 
'SY-FAR-1#', 'Password: |password: ', '.*Press RETURN to get started']

Here, it seems my script found Username:  but it got displayed as PART OF 
_pexpect_session.after  (and this is what I don't understand).  The .before 
or .after data should consist of match before and after the desired keyword 
only.  

= Manual Execution ===
telnet 172.27.161.19 
Trying 172.27.161.19...
Connected to 172.27.161.19.
Escape character is '^]'.


User Access Verification

Username: admin
Password: 

SY-FAR-1en
SY-FAR-1#
=== Python Script Snippet ===

expects = ['yes', '.*Username: ', '.*login: |.*Login: ', 'SY-FAR-1', 
'SY-FAR-1#', 'Password: |password: ', '.*Press RETURN to get started']

i = -1   # reset its value
print *step 1*before match, i = %s % i


self._pexpect_session.timeout = 80
cmd = admin
self._log(Executing CLI: '{0}'.format(cmd))
self._pexpect_session.sendline(cmd)


i = self._pexpect_session.expect(expects)
print *step 2* found index i = %s % i 

print *step 3* after match, exec_cmd expects (%s) = % i, expects
print *step 4* exec_cmd match before: '%s' % 
self._pexpect_session.before
print *step 5* exec_cmd match after: '%s' % 
self._pexpect_session.after 

=== Actual Script Output ==

*step1* before match, i = -1
Executing CLI: 'admin'
*step2* found index i = 1
*step3* after match, exec_cmd expects (1) = ['yes', '.*Username: ', '.*login: 
|.*Login: ', 'SY-FAR-1', 'SY-FAR-1#', 'Password: |password: ', '.*Press RETURN 
to get started']

*step4* exec_cmd match before: ''
*step5* exec_cmd match after: '
Username: '

Appreciate any input or explanation.

Thanks,
Viet
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem with pexpect when executing a command on a remote machine

2014-08-27 Thread Kiran kumar Venkumahanti
Hi,

I am trying to execute a command on a remote machine for which I am using
Python pexpect module. Iam able to connect and copy files to the remote
machine but getting the following error when trying to execute commands on
the remote machine. Please find the below error.


''Error sending command: cluster config -r -a Timeout exceeded in
read_nonblocking().\nscp_ssh_lib.eSSH object at 0xa60cd0\nversion: 2.4
($Revision: 516 $)\ncommand: /usr/bin/ssh\nargs: [\'/usr/bin/ssh\', \'-o\',
\'ServerAliveInterval=60\', \'-o\', \'UserKnownHostsFile=/dev/null\',
\'-o\', \'StrictHostKeyChecking=no\', \'root@192.168.7.1\', \'-p\',
\'22\']\nsearcher: searcher_re:\n0: re.compile((:[^\\r\\n]*
#|[^\\r\\n]*] -| [^\\r\\n]*][$#]|:[^\\r\\n]*[$#]))\nbuffer (last 100
chars):  \x1b[0;10mcluster config -r -a\r\nConfiguration is
OK!\r\nReloading configuration on all nodes\r\n\nbefore (last 100 chars):
 \x1b[0;10mcluster config -r -a\r\nConfiguration is OK!\r\nReloading
configuration on all nodes\r\n\nafter: class
\'pexpect.pexpect.TIMEOUT\'\nmatch: None\nmatch_index: None\nexitstatus:
None\nflag_eof: False\npid: 28817\nchild_fd: 7\nclosed: False\ntimeout:
10\ndelimiter: class \'pexpect.pexpect.EOF\'\nlogfile:
None\nlogfile_read: None\nlogfile_send: None\nmaxread: 2000\nignorecase:
False\nsearchwindowsize: None\ndelaybeforesend: 0.05\ndelayafterclose:
0.1\ndelayafterterminate: 0.1'

If we notice the error, the command is getting properly executed and the
output is also fetched but it returning a TIMEOUT error in
read_nonblocking() function of pxssh.py file of the pexpect module.

Please let me know how can I avoid this. Even the error is not consistent,
sometimes I am able to execute properly but it is failing most of the times.

Kindly reply me as soon as possible.

Thanks in advance.

Regards,
Kiran
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem with pexpect when executing a command on a remote machine

2014-08-27 Thread Chris Angelico
On Thu, Aug 28, 2014 at 1:27 AM, Kiran kumar Venkumahanti
leo.cool...@gmail.com wrote:
 ''Error sending command: cluster config -r -a Timeout exceeded in
 read_nonblocking().\nscp_ssh_lib.eSSH object at 0xa60cd0\nversion: 2.4
 ($Revision: 516 $)\ncommand: /usr/bin/ssh\nargs: [\'/usr/bin/ssh\', \'-o\',
 \'ServerAliveInterval=60\', \'-o\', \'UserKnownHostsFile=/dev/null\',
 \'-o\', \'StrictHostKeyChecking=no\', \'root@192.168.7.1\', \'-p\',
 \'22\']\nsearcher: searcher_re:\n0: re.compile((:[^\\r\\n]*
 #|[^\\r\\n]*] -| [^\\r\\n]*][$#]|:[^\\r\\n]*[$#]))\nbuffer (last 100
 chars):  \x1b[0;10mcluster config -r -a\r\nConfiguration is OK!\r\nReloading
 configuration on all nodes\r\n\nbefore (last 100 chars):  \x1b[0;10mcluster
 config -r -a\r\nConfiguration is OK!\r\nReloading configuration on all
 nodes\r\n\nafter: class \'pexpect.pexpect.TIMEOUT\'\nmatch:
 None\nmatch_index: None\nexitstatus: None\nflag_eof: False\npid:
 28817\nchild_fd: 7\nclosed: False\ntimeout: 10\ndelimiter: class
 \'pexpect.pexpect.EOF\'\nlogfile: None\nlogfile_read: None\nlogfile_send:
 None\nmaxread: 2000\nignorecase: False\nsearchwindowsize:
 None\ndelaybeforesend: 0.05\ndelayafterclose: 0.1\ndelayafterterminate: 0.1'

This is a bit hard to read... but here it is, decoded from repr() format:

Error sending command: cluster config -r -a Timeout exceeded in
read_nonblocking().
scp_ssh_lib.eSSH object at 0xa60cd0
version: 2.4 ($Revision: 516 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', '-o', 'ServerAliveInterval=60', '-o',
'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no',
'root@192.168.7.1', '-p', '22']
searcher: searcher_re:
0: re.compile((:[^\r\n]* #|[^\r\n]*] -| [^\r\n]*][$#]|:[^\r\n]*[$#]))
buffer (last 100 chars):  cluster config -r -a
Configuration is OK!
Reloading configuration on all nodes

before (last 100 chars):  cluster config -r -a
Configuration is OK!
Reloading configuration on all nodes

after: class 'pexpect.pexpect.TIMEOUT'
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 28817
child_fd: 7
closed: False
timeout: 10
delimiter: class 'pexpect.pexpect.EOF'
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1


Do you know why it's timing out?

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pexpect - logging input AND output

2014-08-20 Thread Akira Li
sj.constant...@gmail.com writes:

 i have a script running a few commands on a network device. i can't
 seem to figure out how to log both the input and output of what the
 pexpect script initiates and responds to.

 child = pexpect.spawn ('telnet '+ ip)
 child.expect ('.*:*')
 child.sendline (user)
 child.expect ('.*:*')
 child.sendline (password)
 child.expect(['.*#*', '.**'])
 child.sendline ('enable')
 child.expect (['Password:', '.*#*'])
 child.sendline (password)
 child.expect ('.*#*')
 child.sendline ('conf t')
 child.expect ('.*#*')
 child.sendline ('line vty 0 4')

 i have tried both these logging commands:

 child.logfile = open('log.txt', 'w')
 child.logfile=sys.stdout

 all i get is the input i send with expect/sendline combinations, i
 don't get any of what the device sends, only what i send the device:

 user
 password
 enable
 password
 conf t
 line vty 0 4

 any ideas of what is the correct way to go about this? just can't get the 
 output!

To be clear, expect() doesn't send anything to the device. expect()
matches as little as possible therefore '.*:*' matches *nothing*.

If it is Python 3 then use pexpect.spawnu(). Otherwise, assigning to
child.logfile should work as is.

There is a telnetlib module in stdlib. x/84 python telnet server might
contain a client too.


--
Akira

-- 
https://mail.python.org/mailman/listinfo/python-list


pexpect - logging input AND output

2014-08-14 Thread sj . constantine
i have a script running a few commands on a network device. i can't seem to 
figure out how to log both the input and output of what the pexpect script 
initiates and responds to.

child = pexpect.spawn ('telnet '+ ip)
child.expect ('.*:*')
child.sendline (user)
child.expect ('.*:*')
child.sendline (password)
child.expect(['.*#*', '.**'])
child.sendline ('enable')
child.expect (['Password:', '.*#*'])
child.sendline (password)
child.expect ('.*#*')
child.sendline ('conf t')
child.expect ('.*#*')
child.sendline ('line vty 0 4')

i have tried both these logging commands:

child.logfile = open('log.txt', 'w')
child.logfile=sys.stdout

all i get is the input i send with expect/sendline combinations, i don't get 
any of what the device sends, only what i send the device:

user
password
enable
password
conf t
line vty 0 4

any ideas of what is the correct way to go about this? just can't get the 
output!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pexpect - logging input AND output

2014-08-14 Thread Chris Angelico
On Thu, Aug 14, 2014 at 6:59 PM,  sj.constant...@gmail.com wrote:
 i have a script running a few commands on a network device. i can't seem to 
 figure out how to log both the input and output of what the pexpect script 
 initiates and responds to.

 child = pexpect.spawn ('telnet '+ ip)

If that's not working for you, would it be easier instead to simply
open a socket connection to port 23 on that IP address? Then you'd
just write to the socket (and log what you write) and read from it
(and log that). It's possible you'll see some TELNET or ANSI codes
coming back, but I expect you won't have to send any of them.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pexpect, loading an entry field

2013-08-07 Thread Lakshmipathi.G
Hi -
I'm using Python 2.7.3 (Fedora 17) . I tried a simple example with
pexpect to copy a file to remote system. It works

$ cat pex.py
import pexpect
s = pexpect.spawn ('scp pex.py root@10.30.77.244:/tmp')
s.expect ('Password:')
s.sendline ('a')
s.expect(pexpect.EOF,timeout=20)

Execute above program (change remote ip and password) - If it works
then its not an issue with pexpect or python
environment.


-- 

Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in



On Tue, Aug 6, 2013 at 11:33 PM, inq1ltd inq1...@inqvista.com wrote:


 pexpect looks simple to use. Please check this example


 http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect

 -module-in-python/

  python help;

 

  I am using pexpect to open my program.

  Can someone tell me how to get data to appear in

  an entry field.

  After pexpect opens the my program I have tried to use

  send, sendline, and write functions to try to put data into

  the program's entry field.

  However, the data is going to the terminal window,

  the window that is used to initiate the call to pexpect

  but not to the entry field in the open program.

  I would appreciate suggestions.

 

  jol

 



 Thanks for the response.



 I have been there but that site gives me

 the same information that I get from

 noah.org. I have the pexpect docs and they presume

 that this problem doesn't exist.



 None of the information in the NOAH site or the FAQ's

 address this question.



 I'm using suse linux running python 2.7 and pexpect.



 The data, when using send() method is going to the terminal window,

 This is the same window that is used to initiate the call to pexpect.



 Pexpect opens the program but the send method sends

 data to the terminal window, not the entry field located

 in the child spawned by pexpect.



 interact works, as does close(), TIMEOUT, EOF, before, after,

 expect_exact and methods. But the entry field does not

 load.



 So my question is;



 Why??









 

 

 

  --

  http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


pexpect, loading an entry field

2013-08-06 Thread inq1ltd
python help;

I am using pexpect to open my program.
Can someone tell me how to get data to appear in 
an entry field.

After pexpect opens the my program I have tried to use 
send, sendline, and write functions to try to put data into 
the program's entry field.

However, the data is going to the terminal window, 
the window that is used to initiate the call to pexpect 
but not to the entry field in the open program.

I would appreciate suggestions.
jol

 -- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect, loading an entry field

2013-08-06 Thread Lakshmipathi.G
pexpect looks simple to use. Please check this example
http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python/

-- 

Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in

On Tue, Aug 6, 2013 at 8:35 PM, inq1ltd inq1...@inqvista.com wrote:
 python help;



 I am using pexpect to open my program.

 Can someone tell me how to get data to appear in

 an entry field.



 After pexpect opens the my program I have tried to use

 send, sendline, and write functions to try to put data into

 the program's entry field.



 However, the data is going to the terminal window,

 the window that is used to initiate the call to pexpect

 but not to the entry field in the open program.



 I would appreciate suggestions.

 jol




 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect, loading an entry field

2013-08-06 Thread inq1ltd

 pexpect looks simple to use. Please check this example
 http://www.pythonforbeginners.com/systems-programming/how-to-use-the-
pexpect
 -module-in-python/
  python help;
  
  I am using pexpect to open my program.
  Can someone tell me how to get data to appear in
  an entry field.
  After pexpect opens the my program I have tried to use
  send, sendline, and write functions to try to put data into
  the program's entry field.
  However, the data is going to the terminal window, 
  the window that is used to initiate the call to pexpect
  but not to the entry field in the open program. 
  I would appreciate suggestions.
  
  jol
  

Thanks for the response.

I have been there but that site gives me 
the same information that I get from 
noah.org.  I have the pexpect docs and they presume 
that this problem doesn't exist.

None of the information in the NOAH site or the FAQ's 
address this question. 

I'm using suse linux running python 2.7 and pexpect.

The data, when using send() method is going to the terminal window, 
This is the same window that is used to initiate the call to pexpect.

Pexpect opens the program but the send method sends
 data to the terminal window, not the entry field located
in the child spawned by pexpect.

interact works, as does close(), TIMEOUT, EOF, before, after, 
expect_exact and methods.  But the entry field does not 
load.

So my question is;

Why??




  
  
  
  --
  http://mail.python.org/mailman/listinfo/python-list-- 
http://mail.python.org/mailman/listinfo/python-list


capture html screen with pexpect

2013-07-08 Thread inq1ltd
python help,

I can log into a web site with pexpect but
what I want to do is pipe the opening window 
to a file. 

Logging into the site opens the site window
 but I can't get the window to a file. 

I can't use screen capture I need to get
pexpect to pipe it to a txt file.

Any help will be appreciated.
jimonliinux

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: capture html screen with pexpect

2013-07-08 Thread Dave Angel

On 07/07/2013 01:06 PM, inq1ltd wrote:

python help,

I can log into a web site with pexpect but
what I want to do is pipe the opening window
to a file.

Logging into the site opens the site window
  but I can't get the window to a file.

I can't use screen capture I need to get
pexpect to pipe it to a txt file.



What have you tried?  What environment are you in?  What's the exact 
assignment?


I'd use wget, since I'm on Linux, and it's simple.


davea@think2:~$ wget google.com

creates a file called index.html in my cwd


--
DaveA

--
http://mail.python.org/mailman/listinfo/python-list


pexpect on windows - child process of another child process - quick question

2013-03-09 Thread Z W
Hi All

We have a windows application to install on console mode typing on
cygwin shell app.exe -i console
On Windows process window, we could see this kicks a process named ia
which in turn kicks off ia_launcher to kick off another java.exe
process.
ie

app.exe -- kick off -- ia -- kicks off -- ia_launcher --kicks off
-- java.exe

We like to use pexpect to interact with the ia_launcher process, which
seems to control the stdin/stdout of its own shell window to allow
user to enter responses.
So far, our research shows most examples are related to use of direct
child process, in this case, app.exe process interacting with pexpect.

How do we go about using pexpect to talk to app.exe's grandchild's
shell window ?

We set Don L's expect example where he could set id $spawn_id
between direct child processes but it's still to us how we can
accomplish our goal.

Thanks for your kind help
Sincerely
-- 
http://mail.python.org/mailman/listinfo/python-list


Why is pexpect acting funny with sendline() and expect()?

2012-12-26 Thread saqib . ali . 75
I am running Solaris 5-10, python 2.6.2 and pexpect 2.4

I have the very simple python script below which exercises the functionality of 
sending and receiving text from the shell.

My understanding is that pexepect([pexpect.TIMEOUT, x,y,z], timeout=w) will 
return the index of the match that it found *since the last time pexpect was 
called*, but if it takes longer than w seconds, it will return 0.


Here is my very simple script:


#!/usr/bin/env python

import pexpect
myPrompt =  % 

myShell = pexpect.spawn(/bin/tcsh)
print Sending 'JUNK-0' to shell
x = myShell.sendline(JUNK-0)
y = myShell.expect([pexpect.TIMEOUT], timeout=1)   
print y = %s % y
print myShell.before 
print = * 80
print \n\n
 
for i in range(2):
print i = %d % (i+1)
print Sending 'JUNK-%d' to shell % (i+1)
x = myShell.sendline(JUNK-%d % (i+1))
y = myShell.expect([pexpect.TIMEOUT, myPrompt], timeout=10)  
print y = %s % y
print myShell.before
print = * 80
print \n\n



FYI, my shell prompt is myMachine % , however in this script I have simply 
used  %  to keep it generic.

When I run it, I see the following output: 




Sending 'JUNK-0' to shell
y = 0
JUNK-0
myMachine % JUNK-0
JUNK-0: Command not found.
myMachine % 




i = 1
Sending 'JUNK-1' to shell
y = 1
JUNK-0
myMachine 




i = 2
Sending 'JUNK-2' to shell
y = 1
JUNK-0
JUNK-0: Command not found.
myMachine 





Why do I see JUNK-0 consistently recurring in the output? It should be 
consumed by the first myShell.expect() statement, but it keeps showing up. Why??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pexpect and buffering

2012-12-16 Thread jim . hefferon
Sorry to reply to my own post, but I believe I have my answer and I want to 
help anyone who might google their way here: I need to change PROMPT and 
PROMPT_CONTINUE to be regular expressions, for instance by escaping the periods.


-- 
http://mail.python.org/mailman/listinfo/python-list


Pexpect and buffering

2012-12-15 Thread jim . hefferon
Hello,

I'm trying to use pexpect to grab interactions with Python's REPL.  I am having 
trouble with tracebacks.  Possibly it is related to buffering (hence the 
subject line) but I admit that's a guess.

At the end of this message is a minimal example program.  It feeds three 
commands to a python interpreter.  The second command should fail like this.

 a
Traceback (most recent call last):
  File stdin, line 1, in module
NameError: name 'a' is not defined
 

However, pexpect only returns part of that Traceback .. message, that is, 
pexpect is not waiting for the  prompt.  I have included the output of the 
program below, after the program.  

(In case it helps, spawning Python with -u doesn't make any difference.)

I'd be very glad for any suggestions.
Jim

The program:
--
#!/usr/bin/python
import sys, os, re, pprint
import pexpect

cmds = ['1+2', 'a', '3+4']
PROMPT = ' '
PROMPT_CONTINUE = '... '

child = pexpect.spawn('python')  # start the repl
# child = pexpect.spawn('python', maxread=1)  # makes no difference
child.expect([PROMPT])
print   initial child.before=,pprint.pformat(child.before)
print   initial child.after=,pprint.pformat(child.after)

r = [] 
for cmd in cmds:
print ++ cmd=,pprint.pformat(cmd)
child.sendline(cmd)
dex = child.expect([PROMPT, PROMPT_CONTINUE])
print   child.before=,pprint.pformat(child.before)
print   child.after=,pprint.pformat(child.after)
r.append(child.before)
print r=,pprint.pformat(r)
-

My screen when I run this (Ubuntu 12.04 with Python 2.7.3).

$ ./minex.py
  initial child.before= 'Python 2.7.3 (default, Aug  1 2012, 05:16:07) \r\n[GCC 
4.6.3] on linux2\r\nType help, copyright, credits or license for more 
information.\r\n'
  initial child.after= ' '
++ cmd= '1+2'
  child.before= '1+2\r\n3\r\n'
  child.after= ' '
++ cmd= 'a'
  child.before= 'a\r\nTraceb'
  child.after= 'ack '
++ cmd= '3+4'
  child.before= '(m'
  child.after= 'ost '
r= ['1+2\r\n3\r\n', 'a\r\nTraceb', '(m']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pexpect and buffering

2012-12-15 Thread Chris Rebert
On Dec 15, 2012 4:51 AM, jim.heffe...@gmail.com wrote:

 Hello,

 I'm trying to use pexpect to grab interactions with Python's REPL.  I am
having trouble with tracebacks.  Possibly it is related to buffering (hence
the subject line) but I admit that's a guess.

Why are you doing this in the first place? Why invoke an external Python
shell when you're in a Python program to begin with? Seems terribly
unnecessarily roundabout.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if Pexpect child already exist?

2012-12-05 Thread Dave Angel
On 12/05/2012 02:41 AM, Thomas Elsgaard wrote:
 Hi List

 I am wondering, how can i check if child already exist before i spawn
 ? 

By definition, before you call the spawn, the child doesn't exist.  So
presumably you must mean something else.

 child.isalive() cannot be done on child before it has been spawned.

 ---
 import pexpect

 child=pexpect.spawn('ssh mysurface@192.168.1.105')
 child.sendline('test')
 ---



All we have to do is guess what you really mean.  Do you mean you want
to know if there are any instances of ssh running?  Regardless of how
they got spawned, or from what process?  Or are you trying to determine
if the current process (your script) has any children, of any kind?  Or
what?

Also, you should probably tell what OS and Python versions you're running.

One approach on Linux might be to capture the output of  'ps aux' and
parse it for whatever match criteria you have.

-- 

DaveA

-- 
http://mail.python.org/mailman/listinfo/python-list


How to check if Pexpect child already exist?

2012-12-04 Thread Thomas Elsgaard
Hi List

I am wondering, how can i check if child already exist before i spawn
? child.isalive() cannot be done on child before it has been spawned.

---
import pexpect

child=pexpect.spawn('ssh mysurface@192.168.1.105')
child.sendline('test')
---

Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PExpect Cross-Platform Alternative

2012-09-08 Thread freebee007
Hello Steve,

I was wondering if you had working examples of your automated tasks in python 
... I am asking because I am starting out in Python, and I believe I can save 
my company time and headaches by automating a lot of the tasks we have.
I would like to study your code and see if I can use it in our environment.
Basically, our tasks involve downloading the firmwares and then installing it, 
restarting the processes and making sure all the processes are running. Its on 
Linux servers and HP switches.

I cannot seem to find any example code to learn from ... I have IT guys who 
know Perl, but I do not want to go down that route.

Many thanks,

Zac.


On Thursday, February 11, 2010 8:57:39 PM UTC+1, Steve Holden wrote:
 Nathan Farrar wrote:
  Hello Community,
  
  Recently I've been automating lots of network operations tasks via
  simple python scripts.  Originally, I utilized paramiko but found that
  the module had issues working with cisco equipment.  I switched to
  pexpect and things have worked wonderfully since (I've been running this
  scripts in a Linux environment).  However, I was just tasked to get
  these scripts running in a windows environment and to my dismay very
  quickly realized that pexpect is not cross platform compatible.
  
  Am I stuck, or are there solutions out there?
  
 It works pretty well under Cygwin (which also improves your Windows
 scripting environment no end). Any chance you would be allowed to
 install that?
 
 regards
  Steve
 -- 
 Steve Holden   +1 571 484 6266   +1 800 494 3119
 PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
 Holden Web LLC http://www.holdenweb.com/
 UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Pexpect support with Python3.2.3

2012-04-20 Thread Girish bist
Hi -

I am using the pexpect version 2.4 with Python-3.2.3. I have written a
small script to verify the pexpect support with Python 3.2.3. This
script times out during the system call select execution. Can anyone
please help us with the issue here. The same script is working fine
with Python 2.7.3

thanks,

Script
=
#!/usr/bin/python
import sys
import os

#print (sys.path ,sys.path)
import pexpect
import re
ssh_newkey = 'Are you sure you want to continue connecting'
# my ssh command line

p=pexpect.spawn('ssh galese@172.16.100.232 hostname')

i=p.expect([ssh_newkey,'(P|p)assword:',pexpect.EOF])
print (i *, i)
if i==0:
print (I say yes)
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF]) # this expect
execution goes fine
print (**,p.before,.) # print out the result
print (##,p.after,.)
if i==1:
print (I give password)
p.sendline(galese)
i = p.expect([pexpect.EOF,pexpect.TIMEOUT]) # this expect
execution is timingout
print (i *, i)
print (**,p.before,.) # print out the result
print (##,p.after,.)
elif i==2:
print (I either got key or connection timeout)
pass
print (**,p.before,.) # print out the result
print (##,p.after,.)
print (program complete)
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Saqib Ali

I am using Solaris 10, python 2.6.2, pexpect 2.4

I create a file called me.txt which contains the letters A, B, C
on the same line separated by tabs.

My shell prompt is % 

I then do the following in the python shell:


 import pexpect
 x = pexpect.spawn(/bin/tcsh)
 x.sendline(cat me.txt)
11
 x.expect([pexpect.TIMEOUT, % ])
1
 x.before
'cat me.txt\r\r\nA   B   C\r\n'
 x.before.split(\t)
['cat me.txt\r\r\nA   B   C\r\n']



Now, clearly the file contains tabs. But when I cat it through expect,
and collect cat's output, those tabs have been converted to spaces.
But I need the tabs!

Can anyone explain this phenomenon or suggest how I can fix it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Steven D'Aprano
On Sun, 15 Jan 2012 09:51:44 -0800, Saqib Ali wrote:

 I am using Solaris 10, python 2.6.2, pexpect 2.4
 
 I create a file called me.txt which contains the letters A, B, C
 on the same line separated by tabs.
[...]
 Now, clearly the file contains tabs.

That is not clear at all. How do you know it contains tabs? How was the 
file created in the first place?

Try this:

text = open('me.txt', 'r').read()
print '\t' in text

My guess is that it will print False and that the file does not contain 
tabs. Check your editor used to create the file.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Cameron Simpson
On 15Jan2012 23:04, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 
wrote:
| On Sun, 15 Jan 2012 09:51:44 -0800, Saqib Ali wrote:
|  I am using Solaris 10, python 2.6.2, pexpect 2.4
|  
|  I create a file called me.txt which contains the letters A, B, C
|  on the same line separated by tabs.
| [...]
|  Now, clearly the file contains tabs.
| 
| That is not clear at all. How do you know it contains tabs? How was the 
| file created in the first place?
| 
| Try this:
| 
| text = open('me.txt', 'r').read()
| print '\t' in text
| 
| My guess is that it will print False and that the file does not contain 
| tabs. Check your editor used to create the file.

I was going to post an alternative theory but on more thought I think
Steven is right here.

What does:

  od -c me.txt

show you? TABs or multiple spaces?

What does:

  ls -ld me.txt

tell you about the file size? Is it 6 bytes long (three letters, two
TABs, one newline)?

Steven hasn't been explicit about it, but some editors will write spaces when
you type a TAB. I have configured mine to do so - it makes indentation more
reliable for others. If I really need a TAB character I have a special
finger contortion to get one, but the actual need is rare.

So first check that the file really does contain TABs.

Cheers,
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

Yes Officer, yes Officer, I will Officer. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Saqib Ali

Very good question. Let me explain why I'm not opening me.txt directly
in python with open.

The example I have posted is simplified for illustrative purpose. In
reality, I'm not doing pexpect.spawn(/bin/tcsh). I'm doing
pexpect.spawn(ssh myuser@ipaddress). Since I'm operating on a remote
system, I can't simply open the file in my own python context.


On Jan 15, 2:24 pm, Dennis Lee Bieber wlfr...@ix.netcom.com wrote:
 On Sun, 15 Jan 2012 09:51:44 -0800 (PST), Saqib Ali

 saqib.ali...@gmail.com wrote:
 Now, clearly the file contains tabs. But when I cat it through expect,
 and collect cat's output, those tabs have been converted to spaces.
 But I need the tabs!

 Can anyone explain this phenomenon or suggest how I can fix it?

         My question is:

         WHY are you doing this?

         Based upon the problem discription, as given, the solution would
 seem to be to just open the file IN Python -- whether you read the lines
 and use split() by hand, or pass the open file to the csv module for
 reading/parsing is up to you.

 -=-=-=-=-=-=-
 import csv
 import os

 TESTFILE = Test.tsv

 #create data file
 fout = open(TESTFILE, w)
 for ln in [  abc,
             defg,
             hijA  ]:
     fout.write(\t.join(list(ln)) + \n)
 fout.close()

 #process tab-separated data
 fin = open(TESTFILE, rb)
 rdr = csv.reader(fin, dialect=excel-tab)
 for rw in rdr:
     print rw

 fin.close()
 del rdr
 os.remove(TESTFILE)
 -=-=-=-=-=-=-
 ['a', 'b', 'c']
 ['d', 'e', 'f', 'g']
 ['h', 'i', 'j', 'A']
 --
         Wulfraed                 Dennis Lee Bieber         AF6VN
         wlfr...@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Saqib Ali

The file me.txt does indeed contain tabs. I created it with vi.

 text = open(me.txt, r).read()
 print \t in text
True


% od -c me.txt
000   A  \t   B  \t   C  \n
006


% ls -al me.txt
-rw-r--r--   1 myUsermyGroup   6 Jan 15 12:42 me.txt



On Jan 15, 6:40 pm, Cameron Simpson c...@zip.com.au wrote:
 On 15Jan2012 23:04, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info 
 wrote:
 | On Sun, 15 Jan 2012 09:51:44 -0800, Saqib Ali wrote:
 |  I am using Solaris 10, python 2.6.2, pexpect 2.4
 | 
 |  I create a file called me.txt which contains the letters A, B, C
 |  on the same line separated by tabs.
 | [...]
 |  Now, clearly the file contains tabs.
 |
 | That is not clear at all. How do you know it contains tabs? How was the
 | file created in the first place?
 |
 | Try this:
 |
 | text = open('me.txt', 'r').read()
 | print '\t' in text
 |
 | My guess is that it will print False and that the file does not contain
 | tabs. Check your editor used to create the file.

 I was going to post an alternative theory but on more thought I think
 Steven is right here.

 What does:

   od -c me.txt

 show you? TABs or multiple spaces?

 What does:

   ls -ld me.txt

 tell you about the file size? Is it 6 bytes long (three letters, two
 TABs, one newline)?

 Steven hasn't been explicit about it, but some editors will write spaces when
 you type a TAB. I have configured mine to do so - it makes indentation more
 reliable for others. If I really need a TAB character I have a special
 finger contortion to get one, but the actual need is rare.

 So first check that the file really does contain TABs.

 Cheers,
 --
 Cameron Simpson c...@zip.com.au DoD#743http://www.cskk.ezoshosting.com/cs/

 Yes Officer, yes Officer, I will Officer. Thank you.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Cameron Simpson
On 15Jan2012 16:14, Saqib Ali saqib.ali...@gmail.com wrote:
| The file me.txt does indeed contain tabs. I created it with vi.
| 
|  text = open(me.txt, r).read()
|  print \t in text
| True
| 
| % od -c me.txt
| 000   A  \t   B  \t   C  \n
| 006
| 
| % ls -al me.txt
| -rw-r--r--   1 myUsermyGroup   6 Jan 15 12:42 me.txt

Ok, your file does indeed contain TABs.

Therefre something is turning the TABs into spaces. Pexpect should be
opening a pty and reading from that, and I do not expect that to expand
TABs. So:

  1: Using subprocess.Popen, invoke cat me.txt and check the result
 for TABs.

  2: Using pexpect, run cat me.txt instead of /bin/tcsh (eliminates a
 layer of complexity; I don't actually expect changed behaviour) and
 check for TABs.

On your Solaris system, read man termios. Does it have an expand
TABs mode switch? This is about the only thing I can think of that
would produce your result - the pty terminal discipline is expanding
TABs for your (unwanted!) - cat is writing TABs to the terminal and the
terminal is passing expanded spaces to pexpect. Certainly terminal line
disciplines do rewrite stuff, most obviously \n into \r\n, but a
quick glance through termios on a Linux box does not show a tab
expansion mode; I do not have access to a Solaris box at present.

Cheers,
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

Maintainer's Motto: If we can't fix it, it ain't broke.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Steven D'Aprano
On Sun, 15 Jan 2012 09:51:44 -0800, Saqib Ali wrote:

 I am using Solaris 10, python 2.6.2, pexpect 2.4

Are you sure about that? As far as I can see, pexpect's current version 
is 2.3 not 2.4.


 I create a file called me.txt which contains the letters A, B, C
 on the same line separated by tabs.
 
 My shell prompt is % 
 
 I then do the following in the python shell:
 
 
 import pexpect
 x = pexpect.spawn(/bin/tcsh)

Can you try another shell, just in case tcsh is converting the tabs to 
spaces?

 x.sendline(cat me.txt)
 11

What happens if you do this from the shell directly, without pexpect? It 
is unlikely, but perhaps the problem lies with cat rather than pexpect. 
You should eliminate this possibility.


 x.expect([pexpect.TIMEOUT, % ])
 1
 x.before
 'cat me.txt\r\r\nA   B   C\r\n'


Unfortunately I can't replicate the same behaviour, however my setup is 
different. I'm using pexpect2.3 on Linux, and I tried it using bash and 
sh but not tcsh. In all my tests, the tabs were returned as expected.

(However, the x.expect call returned 0 instead of 1, even with the shell 
prompt set correctly.)



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem while doing a cat on a tabbed file with pexpect

2012-01-15 Thread Michael Torrie
On 01/15/2012 05:11 PM, Saqib Ali wrote:
 
 Very good question. Let me explain why I'm not opening me.txt directly
 in python with open.
 
 The example I have posted is simplified for illustrative purpose. In
 reality, I'm not doing pexpect.spawn(/bin/tcsh). I'm doing
 pexpect.spawn(ssh myuser@ipaddress). Since I'm operating on a remote
 system, I can't simply open the file in my own python context.

There is a very nice python module called paramiko that you could use
to, from python, programatically ssh to the remote system and cat the
file (bypassing any shells) or use sftp to access it.  Either way you
don't need to use pexpect with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Changing the system clock with pexpect confuses pexpect!

2011-12-26 Thread Saqib Ali

See my code below.

I'm controlling a shell logged in as root with pexpect.

The class below has a method (startProc) which spawns a shell and
keeps it alive until told to destroy it (stopProc).

The other 2 methods in this class allow me to change the system clock
and to get the IP Address of this machine.

They all work fine except when I advance the system clock, and
then try to get the IP Address.
In that case, I get an exception because pexpect incorrectly thinks
the output it is getting from ifconfig is invalid. But it is not.
Pexpect is just confused. This doesn't happen when I move the clock
backwards. It only happens when I move the clock forward.

I believe what is going on is that internally pexpect uses the system
clock to keep track of when it receives data from spawned processes.
When I mess with the clock, that messes up the internal workings of
pexpect.

Any suggestions what I should do? I have numerous concurrent pexpect
processes running when I modify the clock. Is there anyway to prevent
them all from getting totally screwed up??

-


#!/usr/bin/env python
import pexpect, os, time, datetime, re

def reportPrint(string):
print string

def reportAssert(condition, string)
if condition == False:
print string
raise Exception


class rootManager:

rootProc = None
rootPrompt = ] % 
myPrompt = ] % 

def __init__(self):
pass




def startProc(self):
if self.rootProc != None:
reportPrint(\t\t- Root Process is already created)
else:
self.rootProc = pexpect.spawn ('/bin/tcsh',)
i = self.rootProc.expect([pexpect.TIMEOUT,
self.myPrompt,])
reportAssert(i != 0, Time-Out exiting)

reportPrint(\t\t- Sending su)
self.rootProc.sendline(su)
i = self.rootProc.expect([pexpect.TIMEOUT, Password: ,])
reportAssert(i != 0, Time-Out exiting)

reportPrint(\t\t- Sending Password)
self.rootProc.sendline(ROOT_PASSWORD)
i = self.rootProc.expect([pexpect.TIMEOUT,
self.rootPrompt,])
reportAssert(i != 0, Time-Out exiting)

reportPrint(\t\t- Root Process created)


def getIPAddr(self):
reportAssert(self.rootProc != None, No active Root Process!)

reportPrint(\t\t- Sending ifconfig -a)
self.rootProc.sendline(ifconfig -a)
i = self.rootProc.expect([pexpect.TIMEOUT, self.rootPrompt,])
reportAssert(i != 0, Time-Out exiting)

outputTxt = self.rootProc.before
ipList = [i for i in re.compile((?=inet )\d{1,3}\.\d{1,3}\.
\d{1,3}\.\d{1,3}).findall(outputTxt) if i != 127.0.0.1]
reportAssert(len(ipList) == 1, Cannot determine IP Address
from 'ifconfig -a': \n%s % outputTxt)
return ipList[0]


def changeClock(self, secondsDelta):
reportAssert(self.rootProc != None, No active Root Process!)

newTime = datetime.datetime.now() +
datetime.timedelta(seconds=secondsDelta)
dateStr = %02d%02d%02d%02d%s % (newTime.month, newTime.day,
newTime.hour, newTime.minute, str(newTime.year)[-2:])
reportPrint(\t\t- Sending 'date %s' command % dateStr)
self.rootProc.sendline(date %s % dateStr)
#Remember, by changing the clock, you are confusing pexpect's
timeout measurement!
# so ignore timeouts in this case
i = self.rootProc.expect([pexpect.TIMEOUT,
self.rootPrompt,],)






def stopProc(self):
if self.rootProc == None:
reportPrint(\t\t- Root Process is already destroyed)
else:

reportPrint(\t\t- Sending exit command)
rootProc.sendline(exit)
i = rootProc.expect([pexpect.TIMEOUT, self.myPrompt])
reportAssert(i != 0, Time-Out exiting)

reportPrint(\t\t- Sending exit command)
rootProc.sendline(exit)
i = rootProc.expect([pexpect.TIMEOUT, pexpect.EOF])
reportAssert(i != 0, Time-Out exiting)
self.rootProc.close()
self.rootProc = None
reportPrint(\t\t- Root Process Destroyed)



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the system clock with pexpect confuses pexpect!

2011-12-26 Thread Roy Smith
In article 
1f342621-0c96-447c-ad5d-f8c9dc777...@i6g2000vbe.googlegroups.com,
 Saqib Ali saqib.ali...@gmail.com wrote:

 I believe what is going on is that internally pexpect uses the system
 clock to keep track of when it receives data from spawned processes.
 When I mess with the clock, that messes up the internal workings of
 pexpect.
 
 Any suggestions what I should do?

Yeah.  Don't mess with the system clock.  Seriously.

There is pretty much no reason for anybody not to be running NTP these 
days.  Every OS ships with it, and there's gazillions of open NTP 
servers to use as references.

NTP will keep your system clock accurate to within a fraction of a 
second and avoid all the horrible problems such as the one you've 
discovered with pexpect when you reset your clock.
-- 
http://mail.python.org/mailman/listinfo/python-list


Can I get use pexpect to control this process?

2011-12-21 Thread Saqib Ali

I have a program X that constantly spews output, hundreds of lines per
minute.
X is not an interactive program. IE: it doesn't take any user input.
It just produces a lot of textual output to STDOUT.

I would like to save the output produced by X into a different file
every 5 seconds regardless of the actual content. I want one file to
contain the output from seconds 0-5, another file should contain 6-10,
etc. etc.

Can I do this with pexpect? I'm not sure I can because the before
argument gives me EVERYTHING upto the most recent match. What I really
need is something that will give me what was produced between the last
2 calls to pexpect.expect().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with really elementary pexpect fragment

2011-12-20 Thread Saqib Ali
Oops! Good call.
Thank you. You pointed out my mistake.


- Saqib




On Tue, Dec 20, 2011 at 12:31 AM, Nick Dokos nicholas.do...@hp.com wrote:

 Saqib Ali saqib.ali...@gmail.com wrote:

 
  I want to write a pexpect script that simply cd's into a directory (~/
  install) and then runs a command from there. It should be so easy.
  But even my cd command is failing. Can't figure out what the problem
  is. The command line prompt is [my machine name here] % 
 
  Here is the code fragment:
 
  print Spawning Expect
  p = pexpect.spawn ('/bin/tcsh',)
 

 If you execute /bin/tcsh by hand, do you get a % prompt?

 Nick

  print Sending cd command
  i = p.expect([pexpect.TIMEOUT, %,])
  assert i != 0, Time-Out exiting
  p.sendline(cd ~/install)
 
  Here is the output:
 
  Spawning Expect
  Sending cd command
  Time-Out exiting
 
 
  How could I be screwing something so simple up??
  --
  http://mail.python.org/mailman/listinfo/python-list
 

-- 
http://mail.python.org/mailman/listinfo/python-list


Need help with really elementary pexpect fragment

2011-12-19 Thread Saqib Ali

I want to write a pexpect script that simply cd's into a directory (~/
install) and then runs a command from there. It should be so easy.
But even my cd command is failing. Can't figure out what the problem
is. The command line prompt is [my machine name here] % 

Here is the code fragment:

print Spawning Expect
p = pexpect.spawn ('/bin/tcsh',)

print Sending cd command
i = p.expect([pexpect.TIMEOUT, %,])
assert i != 0, Time-Out exiting
p.sendline(cd ~/install)

Here is the output:

Spawning Expect
Sending cd command
Time-Out exiting


How could I be screwing something so simple up??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with really elementary pexpect fragment

2011-12-19 Thread Nick Dokos
Saqib Ali saqib.ali...@gmail.com wrote:

 
 I want to write a pexpect script that simply cd's into a directory (~/
 install) and then runs a command from there. It should be so easy.
 But even my cd command is failing. Can't figure out what the problem
 is. The command line prompt is [my machine name here] % 
 
 Here is the code fragment:
 
 print Spawning Expect
 p = pexpect.spawn ('/bin/tcsh',)
 

If you execute /bin/tcsh by hand, do you get a % prompt?

Nick

 print Sending cd command
 i = p.expect([pexpect.TIMEOUT, %,])
 assert i != 0, Time-Out exiting
 p.sendline(cd ~/install)
 
 Here is the output:
 
 Spawning Expect
 Sending cd command
 Time-Out exiting
 
 
 How could I be screwing something so simple up??
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
-- 
http://mail.python.org/mailman/listinfo/python-list


issue with pexpect

2011-10-05 Thread Daniel
Hello,
For about week i am experiencing a problem with pexpect that's why i
hope you can help me :).
Following is my code which tries to remove some files from the root dir
and the code works on linux debian and freebsd but with no success on
linux fedora .. any idea why this happen only in fedora ?

#!/usr/bin/env python
from __future__ import print_function
import sys
import pexpect
import time

spa=pexpect.spawn('su root')
spa.expect('.*')
print(spa.after)
spa.sendline('abc')
spa.expect('.*')
print(spa.after)
spa.sendline('rm -rf /root/py/pe*')
spa.expect('.*')
print(spa.after)
spa.close()


this is the output in Fedora linux  it looks that the script can't
authenticate as root

python]$ ./sk64.py 
Password: 


rm -rf /root/py/pe*


i appreciate any help thanks in advance

-- 
http://mail.python.org/mailman/listinfo/python-list


issue with pexpect

2011-10-05 Thread Daniel
Hello,
For about week i am experiencing a problem with pexpect that's why i
hope you can help me :).
Following is my code which tries to remove some files from the root dir
and the code works on linux debian and freebsd but with no success on
linux fedora .. any idea why this happen only in fedora ?

#!/usr/bin/env python
from __future__ import print_function
import sys
import pexpect
import time

spa=pexpect.spawn('su root')
spa.expect('.*')
print(spa.after)
spa.sendline('abc')
spa.expect('.*')
print(spa.after)
spa.sendline('rm -rf /root/py/pe*')
spa.expect('.*')
print(spa.after)
spa.close()


this is the output in Fedora linux  it looks that the script can't
authenticate as root

python]$ ./sk64.py 
Password: 


rm -rf /root/py/pe*


i appreciate any help thanks in advance 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue with pexpect

2011-10-05 Thread Daniel
there is no such implementation in fedora you can su as a root .. i can
su from regular user to root with no problems 
the problem come when i use the pexpect module

On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote:
 2011/10/5 Daniel 5960...@gmail.com:
  Hello,
  For about week i am experiencing a problem with pexpect that's why i
  hope you can help me :).
  Following is my code which tries to remove some files from the root dir
  and the code works on linux debian and freebsd but with no success on
  linux fedora .. any idea why this happen only in fedora ?
 
  #!/usr/bin/env python
  from __future__ import print_function
  import sys
  import pexpect
  import time
 
  spa=pexpect.spawn('su root')
  spa.expect('.*')
  print(spa.after)
  spa.sendline('abc')
  spa.expect('.*')
  print(spa.after)
  spa.sendline('rm -rf /root/py/pe*')
  spa.expect('.*')
  print(spa.after)
  spa.close()
 
 
  this is the output in Fedora linux  it looks that the script can't
  authenticate as root
 
 
 Hi!
 
 The problem may be that root user is disabled. This was introduced in
 Ubuntu long ago and I believe that later this was also accepted in
 Fedora. That means that you simply can not su to root, no matter
 what password you supply. This is the way how your OS operates and is
 not connected in any way to python or pexpect. Therefore, either use
 sudo (generally recommended) or enable root user (insecure!).
 
 Hope it helps,
 S.Nizamov


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: issue with pexpect

2011-10-05 Thread Daniel
Okey i figure it out how to do the job in fedora
i added slight delay before sending each command
either by the delaybeforesend attribute or by the time module
;)


cheers

On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote:
 2011/10/5 Daniel 5960...@gmail.com:
  Hello,
  For about week i am experiencing a problem with pexpect that's why i
  hope you can help me :).
  Following is my code which tries to remove some files from the root dir
  and the code works on linux debian and freebsd but with no success on
  linux fedora .. any idea why this happen only in fedora ?
 
  #!/usr/bin/env python
  from __future__ import print_function
  import sys
  import pexpect
  import time
 
  spa=pexpect.spawn('su root')
  spa.expect('.*')
  print(spa.after)
  spa.sendline('abc')
  spa.expect('.*')
  print(spa.after)
  spa.sendline('rm -rf /root/py/pe*')
  spa.expect('.*')
  print(spa.after)
  spa.close()
 
 
  this is the output in Fedora linux  it looks that the script can't
  authenticate as root
 
 
 Hi!
 
 The problem may be that root user is disabled. This was introduced in
 Ubuntu long ago and I believe that later this was also accepted in
 Fedora. That means that you simply can not su to root, no matter
 what password you supply. This is the way how your OS operates and is
 not connected in any way to python or pexpect. Therefore, either use
 sudo (generally recommended) or enable root user (insecure!).
 
 Hope it helps,
 S.Nizamov


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect and OpenVMS

2011-06-09 Thread Mark Franklin
I ran into a similar problem. I found throttling self.sh.delaybeforesend works 
for me. I'm on ubuntu.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect: TIMEOUT no longer clears child.before

2011-05-25 Thread Gabriel Genellina
En Thu, 19 May 2011 08:29:21 -0300, Adrian Casey m...@agcasey.com  
escribió:


The behaviour of pexpect has changed between version 2.1 and 2.3.  In  
version 2.1, the following code would result in child.before being  
cleared -:


 child.expect(pexpect.TIMEOUT,1)
 In version 2.3, this is no longer the case.  No matter how many times  
the above code is run, child.before continues to hold the output from  
previous commands.  It is important to be able to clear the contents of  
child.before between each command.  What is the correct way to do this  
in version 2.3?


Try contacting the author: www.noah.org

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list


pexpect: TIMEOUT no longer clears child.before

2011-05-19 Thread Adrian Casey
The behaviour of pexpect has changed between version 2.1 and 2.3.  In 
version 2.1, the following code would result in child.before being 
cleared -:


child.expect(pexpect.TIMEOUT,1)


In version 2.3, this is no longer the case.  No matter how many times 
the above code is run, child.before continues to hold the output from 
previous commands.  It is important to be able to clear the contents of 
child.before between each command.  What is the correct way to do this 
in version 2.3?


Adrian.
--
http://mail.python.org/mailman/listinfo/python-list


Re: stuck with Pexpect script need help!!

2010-12-12 Thread Emile van Sebille

On 12/10/2010 10:02 PM Darshak Bavishi said...
snip

Pexpect is intended for UNIX-like operating systems.)

snip


Can we use pexpect from windows host machine ?!



I expect not...

Emile

--
http://mail.python.org/mailman/listinfo/python-list


Re: stuck with Pexpect script need help!!

2010-12-12 Thread Alexander Kapps

On 12.12.2010 17:06, Emile van Sebille wrote:

On 12/10/2010 10:02 PM Darshak Bavishi said...
snip

Pexpect is intended for UNIX-like operating systems.)

snip


Can we use pexpect from windows host machine ?!



I expect not...

Emile



According to [1] you might get it working with the Cygwin port of 
Python. Alternatively try WinPexpect [2]


[1] http://www.noah.org/wiki/Pexpect#Python
[2] http://bitbucket.org/geertj/winpexpect/wiki/Home
--
http://mail.python.org/mailman/listinfo/python-list


stuck with Pexpect script need help!!

2010-12-10 Thread Darshak Bavishi
Hi Experts,
got ready made code for ssh to unix using python

host machine is windows now when i run this its gives following error :
*
Traceback (most recent call last):
File C:\Python26\pexpect-2.1\pexpect-2.1\pxssh.py, line 1, in module
from pexpect import *
File C:\Python26\pexpect-2.1\pexpect-2.1\pexpect.py, line 83, in module
Pexpect is intended for UNIX-like operating systems.)
ImportError: No module named resource
A critical module was not found. Probably this operating system does not
support it.
Pexpect is intended for UNIX-like operating systems.
  RESTART



Traceback (most recent call last):
File C:\Python26\ssh_session.py, line 7, in module
from pexpect import *
ImportError: No module named pexpect
 *



Can we use pexpect from windows host machine ?!


-- 
BR
Darshak Bavishi
-- 
http://mail.python.org/mailman/listinfo/python-list


I can't seem to change the timeout value on pexpect

2010-12-01 Thread chad
I tried to change the timeout value from 30 to 90 for pexpect in the
following script...

#!/usr/bin/python

import telnetlib
import time
import pexpect

def get_name():
user = raw_input(\nUsername: )
password = raw_input(Password: )
idle(user, password)


def idle(user, password):
child = pexpect.spawn('telnet game.mortalrealms.com 4321')
child.expect(Who art thou:, timeout=90)
child.sendline(user)
print \nEntered username..
child.expect(Password:,timeout=90)
child.sendline(password)
print Entered pass..
child.expect('Press return to continue:', timeout=90)
child.sendline('\n')

if child == 2:
print Connection timeout
elif child == 3:
print Another timeout


#while 1:
child.expect('Druidess Supi burps loudly.')
child.sendline('say oh my aching back')
#time.sleep(15)
#time.sleep(5)
#now.write(\n)

#while 1:
#now.write(wc)
#time.sleep(15)

if __name__ == __main__:
get_name()


However, when I run it, the timeout still shows 30 seconds...

Entered username..
Entered pass..
TrFAvAvaricest):
  File ./mort.py, line 42, in ?
  FAvAvarice
  File ./mort.py, line 10, in get_name
idle(user, password)
  File ./mort.py, line 31, in idle
child.expect('Druidess Supi burps loudly.')
  File /usr/lib/python2.4/site-packages/pexpect.py, line 1311, in
expect
return self.expect_list(compiled_pattern_list, timeout,
searchwindowsize)
  File /usr/lib/python2.4/site-packages/pexpect.py, line 1325, in
expect_list
return self.expect_loop(searcher_re(pattern_list), timeout,
searchwindowsize)
  File /usr/lib/python2.4/site-packages/pexpect.py, line 1409, in
expect_loop
raise TIMEOUT (str(e) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
pexpect.spawn object at 0xb7f6f3cc
version: 2.3 ($Revision: 399 $)
command: /usr/kerberos/bin/telnet
args: ['/usr/kerberos/bin/telnet', 'game.mortalrealms.com', '4321']
searcher: searcher_re:
0: re.compile(Druidess Supi burps loudly.)
buffer (last 100 chars): all.

before (last 100 chars): all.

after: pexpect.TIMEOUT
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 23652
child_fd: 3
closed: False
timeout: 30
delimiter: pexpect.EOF
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1


What am I doing wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Hello, Everyone. I have a problem when using Pexpect module.

2010-11-05 Thread dachuan
hi, everyone.
When I use Pexpect Module, I met the following problem and don't know how to
handle it.
Any advice is appreciated !

My environment:
Linux node08_xen3.4.3_rhel5_1 2.6.18.8-xen #1 SMP Wed Jul 14 17:20:01 CST
2010 i686 i686 i386 GNU/Linux  (FYI: this is a virtual machine.)
Python 2.5.5

and by the way, I have installed pexpect in another machine, and it works
pretty well, its environment is:
Linux WEB1 2.6.9-42.ELlargesmp #1 SMP Wed Jul 12 23:46:39 EDT 2006 x86_64
x86_64 x86_64 GNU/Linux
Python 2.5.5


-bash-3.1$ ./ssh_mutual_trust.py -n
Traceback (most recent call last):
  File ./ssh_mutual_trust.py, line 427, in module
start(sys.argv[1:])
  File ./ssh_mutual_trust.py, line 405, in start
sshkeygen()
  File ./ssh_mutual_trust.py, line 137, in sshkeygen
keygen_child = pexpect.spawn(new_keygen_cmd)
  File /usr/local/lib/python2.5/site-packages/pexpect.py, line 430, in
__init__
self._spawn (command, args)
  File /usr/local/lib/python2.5/site-packages/pexpect.py, line 530, in
_spawn
raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
pexpect.ExceptionPexpect: Error! pty.fork() failed: out of pty devices
-bash-3.1$


-- 
Dachuan Huang, Graduate Candidate
---
Cluster and Grid Computing Lab
Services Computing Technology and System Lab
Huazhong University of Science and Technology
Wuhan, 430074, China
Tel: +86-15902733227

Email: hdc1...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, Everyone. I have a problem when using Pexpect module.

2010-11-05 Thread dachuan
maybe i found why pexpect doesn't work in my environment. (but still, i
don't know how solve it)

my machine is actually a xen domain U, whose kernel is host's kernel.

when I test pexpect module directly on host machine, it works pretty fine.

and that's all I can do about it, maybe pexpect use pseudo-terminal, and
domain U doesn't support this well.

maybe nobody here has encountered this problem before, and i write here just
for everyone's information.

On Fri, Nov 5, 2010 at 2:46 PM, dachuan hdc1...@gmail.com wrote:

 hi, everyone.
 When I use Pexpect Module, I met the following problem and don't know how
 to handle it.
 Any advice is appreciated !

 My environment:
 Linux node08_xen3.4.3_rhel5_1 2.6.18.8-xen #1 SMP Wed Jul 14 17:20:01 CST
 2010 i686 i686 i386 GNU/Linux  (FYI: this is a virtual machine.)
 Python 2.5.5

 and by the way, I have installed pexpect in another machine, and it works
 pretty well, its environment is:
 Linux WEB1 2.6.9-42.ELlargesmp #1 SMP Wed Jul 12 23:46:39 EDT 2006 x86_64
 x86_64 x86_64 GNU/Linux
 Python 2.5.5


 -bash-3.1$ ./ssh_mutual_trust.py -n
 Traceback (most recent call last):
   File ./ssh_mutual_trust.py, line 427, in module
 start(sys.argv[1:])
   File ./ssh_mutual_trust.py, line 405, in start
 sshkeygen()
   File ./ssh_mutual_trust.py, line 137, in sshkeygen
 keygen_child = pexpect.spawn(new_keygen_cmd)
   File /usr/local/lib/python2.5/site-packages/pexpect.py, line 430, in
 __init__
 self._spawn (command, args)
   File /usr/local/lib/python2.5/site-packages/pexpect.py, line 530, in
 _spawn
 raise ExceptionPexpect('Error! pty.fork() failed: ' + str(e))
 pexpect.ExceptionPexpect: Error! pty.fork() failed: out of pty devices
 -bash-3.1$


 --
 Dachuan Huang, Graduate Candidate
 ---
 Cluster and Grid Computing Lab
 Services Computing Technology and System Lab
 Huazhong University of Science and Technology
 Wuhan, 430074, China
 Tel: +86-15902733227

 Email: hdc1...@gmail.com




-- 
Dachuan Huang, Graduate Candidate
---
Cluster and Grid Computing Lab
Services Computing Technology and System Lab
Huazhong University of Science and Technology
Wuhan, 430074, China
Tel: +86-15902733227

Email: hdc1...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect and logging integration

2010-03-11 Thread Lars Stavholm
It works like a charm, thank you!
/Lars

Jean-Michel Pichavant wrote:
 Lars Stavholm wrote:
 Hi all,

 has anyone managed to integrate pexpect and logging?

 I.e., I'd like to be able to pick up the dialog,
 commands sent and responses received, in my logging.
 I know about the pexpect logfile, and I can log things
 to stdout or stderr, but I really need to log using the
 python logging library.

 Any thoughts appreciated
 /Lars

   
 I had to implement this.
 It's a bit of a hack, but it does the job.
 
 The following code is tested with python 2.5, I remember pexpect behaves
 slightly differently in python 2.3.
 
 import logging
 import pexpect
 import re
 
 # this will be the method called by the pexpect object to log
 def _write(*args, **kwargs):
content = args[0]
# let's ignore other params, pexpect only use one arg AFAIK
if content in [' ', '', '\n', '\r', '\r\n']:
return # don't log empty lines
for eol in ['\r\n', '\r', '\n']:
# remove ending EOL, the logger will add it anyway
content = re.sub('\%s$' % eol, '', content)
return logger.info(content) # call the logger info method with the
 reworked content
 
 
 # our flush method
 def _doNothing():
pass
 
 # get the logger
 logger = logging.getLogger('foo')
 
 # configure the logger
 logger.handlers=[]
 logger.addHandler(logging.StreamHandler())
 logger.handlers[-1].setFormatter(logging.Formatter(%(asctime)s -
 %(name)s - %(levelname)s - %(message)s))
 logger.setLevel(logging.INFO)
 
 # give the logger the methods required by pexpect
 logger.write = _write
 logger.flush = _doNothing
 
 p = pexpect.spawn('echo hello world !!', logfile=logger)
 p.expect('!!')
 
 ... 2010-03-10 15:01:31,234 - foo - INFO - hello world !!
 
 Hope it helps.
 
 JM
 
 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect and logging integration

2010-03-10 Thread Jean-Michel Pichavant

Lars Stavholm wrote:

Hi all,

has anyone managed to integrate pexpect and logging?

I.e., I'd like to be able to pick up the dialog,
commands sent and responses received, in my logging.
I know about the pexpect logfile, and I can log things
to stdout or stderr, but I really need to log using the
python logging library.

Any thoughts appreciated
/Lars

  

I had to implement this.
It's a bit of a hack, but it does the job.

The following code is tested with python 2.5, I remember pexpect behaves 
slightly differently in python 2.3.


import logging
import pexpect
import re

# this will be the method called by the pexpect object to log
def _write(*args, **kwargs):
   content = args[0]
   # let's ignore other params, pexpect only use one arg AFAIK
   if content in [' ', '', '\n', '\r', '\r\n']:
   return # don't log empty lines
   for eol in ['\r\n', '\r', '\n']:
   # remove ending EOL, the logger will add it anyway
   content = re.sub('\%s$' % eol, '', content)
   return logger.info(content) # call the logger info method with the 
reworked content



# our flush method
def _doNothing():
   pass

# get the logger
logger = logging.getLogger('foo')

# configure the logger
logger.handlers=[]
logger.addHandler(logging.StreamHandler())
logger.handlers[-1].setFormatter(logging.Formatter(%(asctime)s - 
%(name)s - %(levelname)s - %(message)s))

logger.setLevel(logging.INFO)

# give the logger the methods required by pexpect
logger.write = _write
logger.flush = _doNothing

p = pexpect.spawn('echo hello world !!', logfile=logger)
p.expect('!!')

... 2010-03-10 15:01:31,234 - foo - INFO - hello world !!

Hope it helps.

JM

--
http://mail.python.org/mailman/listinfo/python-list


pexpect and logging integration

2010-03-09 Thread Lars Stavholm
Hi all,

has anyone managed to integrate pexpect and logging?

I.e., I'd like to be able to pick up the dialog,
commands sent and responses received, in my logging.
I know about the pexpect logfile, and I can log things
to stdout or stderr, but I really need to log using the
python logging library.

Any thoughts appreciated
/Lars

-- 
http://mail.python.org/mailman/listinfo/python-list


exp_internal in pexpect

2010-03-03 Thread Pankaj
how to enable expect log in pexpect ? (similar as exp_internal in
expect)
-- 
http://mail.python.org/mailman/listinfo/python-list


timeout restart in pexpect

2010-03-02 Thread Pankaj
I am using pexpect to automate some procedures.

My procedures are time cosuming, some messages coming out from that,
in failure cases it will not output anything.

So I would like to give small timeout value but when some message is
received, it should restart the timeout, similar like
restart_timeout_upon_receive in perl.

Is it possible in Python using pexpect ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PExpect Cross-Platform Alternative

2010-02-12 Thread corey goldberg
  I was just tasked to get
  these scripts running in a windows environment and to my dismay very
  quickly realized that pexpect is not cross platform compatible.
  Am I stuck, or are there solutions out there?


I haven't tried it, but here is another Python implementation of
Expect that claims to run on Windows also:

http://code.google.com/p/python-expect/

-Corey

-- 
http://mail.python.org/mailman/listinfo/python-list


PExpect Cross-Platform Alternative

2010-02-11 Thread Nathan Farrar
Hello Community,

Recently I've been automating lots of network operations tasks via simple
python scripts.  Originally, I utilized paramiko but found that the module
had issues working with cisco equipment.  I switched to pexpect and things
have worked wonderfully since (I've been running this scripts in a Linux
environment).  However, I was just tasked to get these scripts running in a
windows environment and to my dismay very quickly realized that pexpect is
not cross platform compatible.

Am I stuck, or are there solutions out there?

Cheers!
Nathan

-- 
The men the American people admire most extravagantly are the most daring
liars; the men they detest most violently are those who try to tell them the
truth. -- H. L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PExpect Cross-Platform Alternative

2010-02-11 Thread Steve Holden
Nathan Farrar wrote:
 Hello Community,
 
 Recently I've been automating lots of network operations tasks via
 simple python scripts.  Originally, I utilized paramiko but found that
 the module had issues working with cisco equipment.  I switched to
 pexpect and things have worked wonderfully since (I've been running this
 scripts in a Linux environment).  However, I was just tasked to get
 these scripts running in a windows environment and to my dismay very
 quickly realized that pexpect is not cross platform compatible.
 
 Am I stuck, or are there solutions out there?
 
It works pretty well under Cygwin (which also improves your Windows
scripting environment no end). Any chance you would be allowed to
install that?

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where to find pexpect

2009-11-20 Thread yuzhichang
On 10月13日, 下午9时42分, Jean-Michel Pichavant jeanmic...@sequans.com
wrote:
 Antoon Pardon wrote:
  I have been looking forpexpect. The links I find like
 http://pexpect.sourceforge.netall end up at
 http://www.noah.org/wiki/Pexpectwhich produces a 404 not
  found problem.

  Does someone know the current location?

 maybe they removed the distribution so you may use subprocess :o)

 JM

http://pexpect.sourceforge.net seems outdated. I've forked, ported to
Python 3.1, and added more features to pexpect. See 
http://github.com/yuzhichang/pexpect.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is pexpect unmaintained now?

2009-11-20 Thread yuzhichang
On 11月17日, 上午11时40分, yuzhichang yuzhich...@gmail.com wrote:
 Pexpect2.4 is only available at Pypi. Both the homepage 
 ofpexpect(http://www.noah.org/wiki/Pexpect) and download page
 (http://sourceforge.net/projects/pexpect/files/) are outdated. The
 repository on Github (http://github.com/noahspurrier/pexpect/) has
 been removed.

 I ever contacted the author(n...@noah.org) but no response till now.

 I'm going to forkpexpecton Github and add some features...

I've forked, ported it to Python 3.1, and added some features. See
http://github.com/yuzhichang/pexpect.

Regards,
Zhichang Yu
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >