ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python3.10实现Telnet

2022-05-09 19:02:10  阅读:299  来源: 互联网

标签:Python3.10 实现 ip Telnet tn 命令 command user result


"""说明:
调用示例:
result = telnet_connect(ip_host='地址', ip_port='端口(默认23)', ip_user='用户名', ip_password='密码', ip_command=['命令1', '命令2'])
print(result)
建议采用关键字方式传递调用参数。
调用参数说明:
telnet_connect(ip_host, [ip_port], ip_user, ip_password, [ip_command[]])
ip_hont 字符串格式 必选参数 指定Telnet目的地址;
ip_port 字符串格式 可选参数 指定Telnet端口 默认值23;
ip_user 字符串格式 必选参数 指定远程登录用户名;
ip_password 字符串格式 必选参数 指定远程登录密码;
ip_command 列表格式,每个元素为字符串 可选参数 指定登录后执行的命令,每个元素为一条命令 默认由用户接管命令输入
返回值说明:
如远程设备无法通过Telnet连接 返回:'远程连接失败!'
如远程设备登陆失败 返回:'登陆失败!'
如命令执行成功 返回:命令执行后的输出结果 执行多条命令时,将在最后一条命令执行完成后一次返回全部结果
用户操作退出 返回:'用户退出。'
其他说明:
执行命令过程中不会判断命令是否执行成功;
如命令返回信息不能在一页内显示完,只显示部分内容。

"""
# _*_coding:utf-8_*_


import telnetlib
import time


def telnet_connect(ip_host, ip_user, ip_password, ip_port='23', ip_command=['user_control']):
try:
tn = telnetlib.Telnet(host=ip_host, port=ip_port, timeout=1) # 启动Telnet连接
except:
return '远程连接失败!'
else:
time.sleep(0.5) # 等待远端设备输出
print(tn.read_very_eager().decode())
tn.read_until(b'Username: ', timeout=0.5) # 等待提示Username,等待1秒
tn.write(ip_user.encode() + b"\n") # 输入用户名
time.sleep(0.5) # 等待远端设备输出
print(tn.read_very_eager().decode())
tn.read_until(b"Password: ", timeout=0.5) # 等待提示Password,等待1秒
tn.write(ip_password.encode() + b"\n") # 输入密码
time.sleep(0.5) # 等待远端设备输出
print(tn.read_very_eager().decode())
v_result = tn.read_very_eager().decode() # 接收登录返回结果
if 'failed' in v_result:
return '登录失败!'
else:
tel_result = ''
if ip_command[0] == 'user_control':
print('现在开始交由用户控制' + "\n")
# tn.interact()
while True:
time.sleep(0.1)
from pip._vendor.distlib.compat import raw_input
user_command = raw_input('请输入命令:')
time.sleep(0.2)
if user_command == 'exit':
print('用户退出。')
break
else:
tn.write(user_command.encode() + b"\n") # 执行每条命令
time.sleep(0.5)
tel_result = (tn.read_very_eager().decode() + "\n") # 输出命令执行结果
print(tel_result + "\n") # 输出命令执行结果)
tn.close()
else:
for cmd in ip_command:
tn.write(cmd.encode() + b"\n") # 执行每条命令
time.sleep(1)
tel_result = tel_result + tn.read_very_eager().decode() + "\n"
tn.close()
return tel_result
# print(telnet_connect(ip_host='1.1.1.1', ip_user='admin', ip_password='admin'))

标签:Python3.10,实现,ip,Telnet,tn,命令,command,user,result
来源: https://www.cnblogs.com/wh0305/p/16250414.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有