python学习吧 关注:15,384贴子:75,504
  • 0回复贴,共1

pythno对接-手动_端口恢复

只看楼主收藏回复

# -*- coding: utf-8 -*-
import re
import telnetlib
import time
def get_all_info(tn, command):
command = bytes(command, encoding='utf-8')
tn.write(command + b'\n')
time.sleep(1)
result_list = []
while (True):
command_result = tn.read_very_eager().decode('ascii')
result_list.append(command_result)
if re.findall(r"--More--", command_result.strip()):
tn.write(b" ")
elif re.findall(r"#", command_result.strip()):
break
else:
time.sleep(0.05)
continue
result_str = "\n".join(result_list)
return result_str
def get_info_telnet(host_ip, username, password):
tn = telnetlib.Telnet()
try:
tn.open(host_ip, port=23, timeout=5)
print('%s connected ssuccess !' % host_ip)
tn.read_until(b'Username:', timeout=5)
tn.write(username.encode('ascii') + b'\n')
tn.read_until(b'Password:', timeout=5)
tn.write(password.encode('ascii') + b'\n')
time.sleep(1)
command_result = tn.read_until(b'#', timeout=5)
if b'#' not in command_result:
print('%s登录失败' % host_ip)
else:
print('%s登录成功' % host_ip)
except:
print('%s网络连接失败' % host_ip)
command = f"config terminal interface {port} no shutdown end write"
cint_info = get_all_info(tn, command)
print(f"返回结果:\n{cint_info}")
tn.close()
if __name__ == '__main__':
host_ip = ''
username = ''
password = ''
port = '' # 端口
get_info_telnet(host_ip, username, password, port)


IP属地:广东1楼2024-10-10 18:55回复