其中telnet模块源码如下:
# Telnet {{{ usage_hints = ( available_options = ( Response = Response_Base def connect(self, host, port, timeout): return TCP_Connection(fp) def execute(self, host, port='23', inputs=None, prompt_re='\w+:', timeout='20', persistent='1'): fp, _ = self.bind(host, port, timeout=timeout) trace = '' if self.prompt_count == 0: _, _, raw = fp.expect([prompt_re], timeout=timeout) if persistent == '0': mesg = repr(raw)[1:-1] # strip enclosing single quotes # }}} |
把核心部分抽出来,流程是这样的。
创建一个连接到telnetlib.Telnet对象fp -->> 等待出现匹配正则(\w+:)字符出现(如 login:,username等)
-->> 发送用户名 -->>继续等待(\w+:)出现(如passwd:,Password:) -->> 发送密码 ->> 等待(\w+:)出现,输出返回字符串
过程就是这么简单,其中expect函数接受二个参数,第一个是正则表达式的列表,可以是编译好的,也可以是字符串,第二个是超时时间。
返回一个三项的tuple,第一个是匹配到的正则序号(从0开始),第二个是匹配match的对象,第三个是直到正则的返回数据(包括匹配内容)
这说的有点抽象。
请看下面: