有人可以帮助我使用此代码吗?
我只是不知道为什么它不起作用。在控制台上,输入命令cat /var/log/messages* |head -10
返回我要查看的10行-在这里,我总是得到” return!”。
import telnetlib
import time
def GetLogs(name, path):
tempStr=''
HOST = name
user = "root"
password = "asdf"
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
tn.read_until(b'Password: ')
time.sleep(1)
tn.write(password.encode('ascii') + b"\n")
time.sleep(2)
PATH_TO_LOG = "cat " + path + "\n"
tn.write(PATH_TO_LOG.encode('ascii') + b"\n")
tn.write(b"exit\n")
tempStr=tn.read_all().decode('ascii')
return tempStr.replace("\n", "<br>")
print(GetLogs("tb2-dm2", "/var/log/messages* |head -10"))
可悲的是,在其他主题中给出的答案无济于事,因为它始终是同一个问题-没有连接关闭-但是我在这里做了
答案 0 :(得分:0)
也许您可以尝试以下代码:
import telnetlib
import time
import getpass
import sys
COMMAND = sys.argv[1].encode('utf-8')
USER = input('Username: ').encode('utf-8')
PASSWORD = getpass.getpass().encode('utf-8')
ENABLE_PASS = getpass.getpass(prompt='Enter enable password: ').encode('utf-8')
IP = ""
print('Connection to device {}'.format(IP))
with telnetlib.Telnet(IP) as t:
t.read_until(b'Username:')
t.write(USER + b'\n')
t.read_until(b'Password:')
t.write(PASSWORD + b'\n')
t.write(b'enable\n')
t.read_until(b'Password:')
t.write(ENABLE_PASS + b'\n')
t.write(b'terminal length 0\n')
t.write(COMMAND + b'\n')
time.sleep(5)
output = t.read_very_eager().decode('utf-8')
print(output)
对我有用