我目前正在构建一个python脚本,该脚本启用和禁用交换机上的某些端口,以查看交换机如何实现质量保证。我一直在使用一个名为paramiko的Python库,它实现了SSH来连接到我想要的任何设备,我指的是我的一个队友交付的遗留代码来编写更多的脚本。在一个遗留代码文件中,有一个名为_run_poll的函数,我不太清楚它到底在做什么
我已经尝试过研究“轮询”对SSH的意义,但我仍然不了解在运行“轮询”时会发生什么。它的定义似乎有点模糊。以下是函数:
def _run_poll(self, session, timeout, input_data):
interval = 0.1
maxseconds = timeout
maxcount = maxseconds / interval
i = 0
timeout_flag = False
self.info('polling (%d, %d)' % (maxseconds, maxcount))
start = datetime.datetime.now()
start_secs = time.mktime(start.timetuple())
output = ''
session.setblocking(0)
while True:
if session.recv_ready(): # returns true if data has been buffered
data = session.recv(self.bufsize) # receive data from the channel
output += data
self.info('read %d bytes, total %d' % (len(data), len(output)))
if session.send_ready():
# We received a potential prompt.
# In the future this could be made to work more like
# pexpect with pattern matching.
if i < len(input_data):
data = input_data[input_idx] + '\n'
i += 1
self.info('sending input data %d' % (len(data)))
session.send(data)
self.info('session.exit_status_ready() = %s' % (str(session.exit_status_ready())))
if session.exit_status_ready():
break
# Timeout check
now = datetime.datetime.now()
now_secs = time.mktime(now.timetuple())
et_secs = now_secs - start_secs
self.info('timeout check %d %d' % (et_secs, maxseconds))
if et_secs > maxseconds:
self.info('polling finished - timeout')
timeout_flag = True
break
time.sleep(0.200)
self.info('polling loop ended')
if session.recv_ready():
data = session.recv(self.bufsize)
output += data
self.info('read %d bytes, total %d' % (len(data), len(output)))
self.info('polling finished - %d output bytes' % (len(output)))
if timeout_flag:
self.info('appending timeout message')
output += '\nERROR: timeout after %d seconds\n' % (timeout)
session.close()
return output
我找不到太多的在线资源来描述这里发生了什么或关于“投票”的一般情况。有谁能帮我解释一下什么是“投票”以及这里发生了什么
在编程中有两种处理异步事件的方法
一种方法是使用中断:您的代码在被某种机制“唤醒”之前不会执行,然后执行。必须在低于代码执行位置的级别上支持此机制。例如,微控制器具有内置的特定硬件,可以中断应用程序并跳转到特定地址以开始执行指令以处理中断
构建一个中断系统是很困难的,并且需要大量的工作。对于某些应用程序,这是不可能的。几乎总是更容易(尽管效率较低)轮询,或者反复检查一个条件,直到它变为真,然后继续执行其他操作
在您的示例中,请注意他是如何使用
while True:
循环的。True永远不会为False,因此这个while循环只能由break
语句中断。我们在因此,代码的作者决定不断地做一些事情,直到
session.exit_status_ready()
为真。由于这是paramiko,他很可能通过SSH执行了一个远程命令,并等待该命令完成并返回退出代码。这个循环的目的是让程序一直卡在循环中,直到命令执行完毕并返回结果。它还可以超时:因此,如果命令花费的时间超过
maxseconds
,程序将不会永远等待一旦退出循环,它将打印:
因此,当您看到此消息时,您知道远程命令已完成执行或超时
轮询的目的是反复检查某些内容,直到出现某种情况。在您的情况下,该条件是“远程命令已完成执行”或“已过一定时间”
维基百科关于Polling的文章将其定义为:
在您的代码中,这意味着它会定期(每200ms)检查SSH连接是否有任何传入数据和输出队列中的空闲容量
相关问题 更多 >
编程相关推荐