Pexpect.spawn ssh and cron (Solaris)



我在Solaris 10上使用cron运行pexpect脚本时遇到问题,该脚本将ssh连接到其他设备。我正在连接的设备是网络元件,它们将使用user/pass接受ssh连接(但我无法重新配置它们)。

我有一个脚本,当我从登录shell运行时运行良好,但当从cron运行时失败。我读过关于将env设置为模拟交互式shell的帖子,但没有用。非常感谢您的帮助。我仅限于使用python2.6、pexpect和Solaris10。

脚本是:/path_to/try.py

#!/usr/bin/env python
import pexpect
import traceback
import os, sys, time, re
from time import sleep
host='10.0.0.58'
user='myuser'
password='password'
child=pexpect.spawn("/usr/bin/ssh -l %s %s" % (user, host))
i = child.expect([pexpect.EOF, pexpect.TIMEOUT, "password: "])
if i == 0:
    print "EOF ERROR SSH could not login %s . Here is what SSH said:"% (host)
    print child.before, child.after
if i == 1:  # Timeout
    print "TIMEOUT ERROR SSH could not login. Here is what SSH said:" % (host)
    print child.before, child.after
if i == 2:
    child.sendline(password)
    print "Got device password prompt"
print "finally"
exit;

crontab是:

42 * * * * PATH=$PATH:/usr/local/bin && bash -lc "/path_to/try.py" 

通过cron的脚本结果,即:

EOF ERROR SSH could not login 10.0.0.58 . Here is what SSH said:
 <class 'pexpect.EOF'>
<pexpect.spawn object at 0x8ed30>
version: 2.3 ($Revision: 399 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'myuser', '10.0.0.58']
searcher: searcher_re:
    0: EOF
    1: TIMEOUT
    2: re.compile("password: ")
buffer (last 100 chars):
before (last 100 chars):
after: <class 'pexpect.EOF'>
match: <class 'pexpect.EOF'>
match_index: 0
exitstatus: None
flag_eof: True
pid: 18189
child_fd: 3
closed: False
timeout: 300
delimiter: <class '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
finally

我找到了一个解决方案,将pexpect从2.3升级到4.1(并安装它的依赖项ptyprocess-0.5.1)。

最新更新