Python telnet编程代码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python telnet编程代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1671字,纯文字阅读大概需要3分钟。
内容图文
Python telnet 编程
Python自带 telnetlib 模块,可以用于编写telnet**客户端**连接,遵循**RFC 854: TELNET Protocol Specification** 协议。python 中定义了telnet 格式,可以未交互式telnet客户端,也可以采用发送命令,并获取命令执行结果的方式。
采用交互式方式调用,直接采用interact 方法即可,在采用非交互方式,建议采用read_until 确定信令执行。具体实现间如下代码。
class telnetclass(object):
def __init__(self):
self.tc = telnetlib.Telnet()
self.tc.set_debuglevel(10)
def log_in(self,ip=None,type=None):
# logging.info("正在连接epack")
self.tc.open(ip,23)
# time.sleep(4)
self.tc.read_until(b‘login: ‘,timeout=10)
self.tc.write("root".encode(‘ascii‘) + b‘\n‘)
self.tc.read_until(b"hytera",timeout=120)
logging.info("%s 登录成功"%ip)
# result = print(self.tc.read_all().decode(‘ascii‘))
# return result
# # time.sleep(4)
def execute_command(self,cmd,lag=‘‘):
"""
cmd 表示要执行的命令
lag:命令执行后应该具有的信息,用于表示命令执行成功
"""
# self.tc.read_until(b‘# ‘,timeout=60)
logging.info("执行命令{} ".format(cmd))
self.tc.write(cmd.encode(‘ascii‘)+b‘\n‘)
# time.sleep(90)
cmd_result = self.tc.read_eager().decode("ascii")
self.tc.read_until(lag.encode(‘ascii‘))
logging.info("{}执行结果为 {}".format(cmd,cmd_result))
# logging.info("{}执行完成".format(cmd))
return cmd_result
def execute_command_wait(self,cmd,fp,wait_time=900):
"""
用于执行命令 等待命令执行时间,将结果写入文件内
"""
logging.info("执行命令{} ".format(cmd))
self.tc.write(cmd.encode(‘ascii‘)+b‘\n‘)
time.sleep(int(wait_time))
cmd_result = self.tc.read_very_eager().decode("ascii")
time_stamp = time.asctime()
fp.write(time_stamp)
fp.write("\n")
fp.write(cmd_result)
logging.info("{}执行结果为 {}".format(cmd,cmd_result))
# logging.info("{}执行完成".format(cmd))
# return cmd_result
# 退出telnet
def logout_host(self):
self.tc.write(b"exit\n")
原文:https://www.cnblogs.com/Finding-bugs/p/14172646.html
内容总结
以上是互联网集市为您收集整理的Python telnet编程代码全部内容,希望文章能够帮你解决Python telnet编程代码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。