python pexpect:SSHing然后更新日期
我终于让我的python pexpect脚本正常工作了,除了更新日期的最重要部分!我可以在框中使用SSH,但我的第二个命令没有正确执行。我一直把头撞在墙上想弄清楚原因。我已经检查了sting的输出,它应该根据编码工作。我不是python或pexpect方面的专家,所以我需要一些帮助来弄清楚为什么我的时间没有更新 我的原始代码:python pexpect:SSHing然后更新日期,python,ssh,pexpect,Python,Ssh,Pexpect,我终于让我的python pexpect脚本正常工作了,除了更新日期的最重要部分!我可以在框中使用SSH,但我的第二个命令没有正确执行。我一直把头撞在墙上想弄清楚原因。我已经检查了sting的输出,它应该根据编码工作。我不是python或pexpect方面的专家,所以我需要一些帮助来弄清楚为什么我的时间没有更新 我的原始代码: list = ["089"] sn = 0 ssh_new_conn = 'Are you sure you want to continue connecting'
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().
新代码:
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().
我遇到新错误:
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().
您可能应该处理sudo密码提示(+
-t
ssh选项以获取tty),并在p.close()之前使用p.expect(EOF)
,以避免过早终止子进程
以下是一个基于以下内容的示例:
您也可以尝试:
用法:
$ fab -H localhost,user@host date
错误解决方案
我想出了解决我所犯错误的办法。由于一个已知的bug,我不得不在usr/lib/python.2.6/dist-packages/pxsh.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
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
对于像我这样在2019年坚持使用Python2.6并且不想攻击他们的站点包的可怜人,我能够通过在构造函数中将maxread设置为1来解决这个问题
pxsh.pxsh(maxread=1)
@Sebastian我尝试了你所说的,但是我一直遇到s.login(主机名、用户名、密码)
的问题。我仔细检查了传递给该函数的值,所有内容看起来都是正确的。我甚至试着从你提供的链接中运行示例代码,代码错误出现在同一行。@Sebastian请查看我的原始帖子,了解我的最新更新code@Sebastian请检查我的错误,我原来的职位getting@Sebastian我找到了解决我所犯错误的方法。我将运行一个快速测试,以确保其他一切正常工作。如果一切正常,那么我将在今天将您的答案标记为正确。更新您的pexpect版本,例如,要安装到~/.local
,请运行:pip安装--user pexpect
。超时应该由pexpect自己处理。@Sebastian bypip
你的意思是python pip
?是的。至于我,那行代码只用于清除ssh登录发出的所有缓冲区。之后,它们发送空命令以引发另一个提示输出。因此,我相信行可以简单地包装到try except pass
中,以便在输入中没有任何内容时忽略大小写。