6

我终于让我的 python pexpect 脚本工作了,除了最重要的部分更新日期!我可以在框中进行 SSH,但我的第二个命令无法正确执行。我一直在用头撞墙试图找出原因。我检查了刺痛的输出,它应该根据编码的内容工作。我不是 python 或 pexpect 方面的专家,所以我需要一些帮助来弄清楚为什么我的时间没有更新。

我的原始代码

list = ["089"]
sn = 0

ssh_new_conn = 'Are you sure you want to continue connecting'

class ThreadClass(threading.Thread):
def __init__(self, index):
super(ThreadClass, self).__init__()
self.index = index
def run(self):

sn = storelist[self.index]


#easterndate = (currenttime + datetime.timedelta(0, 3600))
#easterndate = easterndate

est = timezone('US/Eastern')
cst = timezone('US/Central')
#currenttime = (datetime.now())
currenttime = cst.localize(datetime.now())
#easterndate = (currenttime + timedelta(0, 3600))
#easterndate = easterndate.strftime("%a %b %d %H:%M:%S %Z %Y")
easterndate = currenttime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
command1 = "/usr/bin/ssh %(username)s@%(hostname)s" % locals()
command2 = " sudo date -s\"%(easterndate)s\"" % locals()
command3 = " sudo date -s\"%(currenttime)s\"" % locals()
now = datetime.now()

#central
if sn == "073" or sn == "066" or sn == "016": #or sn == "022":
    p = pexpect.spawn((command1 + command3), timeout=360)


#eastern
else:
    print(command1 + command2)
    p = pexpect.spawn((command1 + command2), timeout=360)


# Handles the 3 possible connection outcomes:
# a) Ssh to the remote host for the first time, triggering 'Are you sure you want to continue connecting'
# b) ask you for password
# c) No password is needed at all, because you already have the key.
i = p.expect([ssh_new_conn,'[pP]assword:',pexpect.EOF])
print ' Initial pexpect command output: ', i
if i == 0:
    # send 'yes'
    p.sendline('yes')
    i = p.expect(['[pP]assword:',pexpect.EOF])
    print 'sent yes. pexpect command output', i
    if i == 0:
        # send the password
        print "logging into box %(sn)s" % locals()
        p.sendline(password)
        print "login successful"
        print "Setting the time..."

elif i == 1:
    # send the password
    print "logging into box %(sn)s" % locals()
    p.sendline(password)
    print "login successful"
    print "Setting the time..."
    p.close()

elif i == 2:
    print "pexpect faced key or connection timeout"
    pass

print p.before

for i in range(len(list)):
  t = ThreadClass(i)
  t.start()

新代码

class ThreadClass(threading.Thread):
def __init__(self, index):
   super(ThreadClass, self).__init__()
   self.index = index
def run(self):

    try:
        sn = storelist[self.index]
        username = raw_input('username: ')
        password = raw_input('password: ')
        hostname = "[hostname]"
        est = timezone('US/Eastern')
        cst = timezone('US/Central')
        #currenttime = (datetime.now())
        currenttime = cst.localize(datetime.now())
        #easterndate = (currenttime + timedelta(0, 3600))
        #easterndate = easterndate.strftime("%a %b %d %H:%M:%S %Z %Y")
        easterndate = currenttime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
        ssh = pxssh.pxssh()

        print(hostname + " " + username + " " + password)
        ssh.login(hostname, username, password)

        if sn == "073" or sn == "066" or sn == "016": #or sn == "022":
            ssh.sendline ('date')       # run a command
            ssh.prompt()                # match the prompt
            print(s.before)           # print everything before the prompt.
            ssh.sendline ('sudo date -s\"%(currenttime)s\"' % locals())  # run a command
            ssh.expect('(?i)password.*:')  # match password prompt for sudo
            ssh.sendline(password)
            ssh.prompt()
            print(s.before)
            ssh.logout()
        else:
            ssh.sendline ('date')       # run a command
            ssh.prompt()                # match the prompt
            print(s.before)           # print everything before the prompt.
            ssh.sendline ('sudo date -s\"%(easterndate)s\"' % locals())  # run a command
            ssh.expect('(?i)password.*:')  # match password prompt for sudo
            ssh.sendline(password)
            ssh.prompt()
            print(s.before)
            ssh.logout()

    except pxssh.ExceptionPxssh as e:
        print(e)


for i in range(len(storelist)):
  t = ThreadClass(i)
  t.start()

我得到的新错误

Traceback (most recent call last):
  File "./sshtest.py", line 8, in <module>
    s.login (hostname, username, password)
  File "/usr/lib/python2.6/dist-packages/pxssh.py", line 243, in login
    if not self.synch_original_prompt():
  File "/usr/lib/python2.6/dist-packages/pxssh.py", line 134, in synch_original_prompt
    self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
  File "/usr/lib/python2.6/dist-packages/pexpect.py", line 824, in read_nonblocking
    raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().

错误的解决方案

我想出了解决我遇到的错误的方法。由于一个已知的错误,我不得不将以下行添加到 usr/lib/python.2.6/dist-packages/pxssh.py:

self.sendline()       #line 134
time.sleep(0.5)       #line 135
self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
4

3 回答 3

2

错误的解决方案

我想出了解决我遇到的错误的方法。由于一个已知的错误,我不得不将以下行添加到 usr/lib/python.2.6/dist-packages/pxssh.py:

self.sendline()       #line 134
time.sleep(0.5)       #line 135
self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
于 2014-02-24T22:12:26.527 回答
1

您可能应该处理 sudo 密码提示(+ -tssh 选项以获取 tty)并使用p.expect(EOF)beforep.close()以避免过早终止子进程。

这是一个基于pexpect docs的示例:

import pxssh
try:
    s = pxssh.pxssh()
    s.login (hostname, username, password)
    s.sendline ('date')       # run a command
    s.prompt()                # match the prompt
    print(s.before)           # print everything before the prompt.
    s.sendline ('sudo date')  # run a command
    s.expect('(?i)password.*:')  # match password prompt for sudo
    s.sendline(password)
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print(e)

您也可以尝试fabric

# fabfile.py
from fabric.api import run, sudo

def date():
    run('date')
    sudo('date')

用法:

$ fab -H localhost,user@host date
于 2013-04-09T22:48:49.960 回答
0

对于像我这样在 2019 年坚持使用 python 2.6 并且不想破解他们的站点包的其他可怜的灵魂,我能够通过在构造函数中将 maxread 设置为 1 来解决这个问题。

pxssh.pxssh(maxread=1)

于 2019-03-01T21:56:55.467 回答