Python 으로 telnet 원격(텔넷 서버)으로 접속하여 제어 하고 싶다면
Python 기본 라이브러리인 telnetlib 사용 방법을 간략하게 소개해보려고 한다.
Python이 설치 되어있다면 telnetlib을 따로 설치할 필요없다.
>>> import telnetlib
>>> import socket
>>> HOST = '127.0.0.1' # telnet으로 접속할 대상
>>> PORT = '23' # telnet port: 23
>>> SESSION_TIMEOUT = None
>>> session = telnetlib.Telnet(HOST, PORT, SESSION_TIMEOUT)
>>>
>>> def nego(sock, cmd, opt):
if cmd == telnetlib.WILL and opt == telnetlib.ECHO:
sock.sendall(telnetlib.IAC + telnetlib.DO + telnetlib.ECHO)
elif cmd in (telnetlib.DO, telnetlib.DONT):
sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
elif cmd in (telnetlib.WILL, telnetlib.WONT):
sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
>>> session.set_option_negotiation_callback(nego)
>>>
>>> session.write('show interface summary'.encode('ascii') + b"\n")
>>>
>>> msgs = []
>>> while True:
msgs += [session.read_eager().decode('ascii')]
if msgs[-1] == '':
break
>>>
>>>
>>>
>>> print(''.join(msgs))
show interface summary
*: interface is up
IHQ: pkts in input hold queue IQD: pkts dropped from input queue
OHQ: pkts in output hold queue OQD: pkts dropped from output queue
RXBS: rx rate (bits/sec) RXPS: rx rate (pkts/sec)
TXBS: tx rate (bits/sec) TXPS: tx rate (pkts/sec)
TRTL: throttle count
Interface IHQ IQD OHQ OQD RXBS RXPS TXBS TXPS TRTL
-----------------------------------------------------------------------------------------------------------------
* GigabitEthernet1 0 0 0 0 0 0 0 0 0
GigabitEthernet2 0 0 0 0 0 0 0 0 0
GigabitEthernet3 0 0 0 0 0 0 0 0 0
GigabitEthernet4 0 0 0 0 0 0 0 0 0
GigabitEthernet5 0 0 0 0 0 0 0 0 0
GigabitEthernet6 0 0 0 0 0 0 0 0 0
GigabitEthernet7 0 0 0 0 0 0 0 0 0
* GigabitEthernet8 0 0 0 0 4000 8 0 0 0
* Loopback0 0 0 0 0 0 0 0 0 0
* Loopback1 0 0 0 0 0 0 0 0 0
* Loopback2 0 0 0 0 0 0 0 0 0
IOSXE#
>>>
>>>
>>> session.close()
>>>
session = telnetlib.Telnet(HOST, PORT, SESSION_TIMEOUT)
>>> def nego(sock, cmd, opt):
if cmd == telnetlib.WILL and opt == telnetlib.ECHO:
sock.sendall(telnetlib.IAC + telnetlib.DO + telnetlib.ECHO)
elif cmd in (telnetlib.DO, telnetlib.DONT):
sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
elif cmd in (telnetlib.WILL, telnetlib.WONT):
sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
>>> session.set_option_negotiation_callback(nego)
>>>
command 명령의 끝
이라는 것을 알려는 문자를 넣어줘야됩니다.\n
: new line>>> session.write('show interface summary'.encode('ascii') + b"\n")
>>>
>>> msgs = []
>>> while True:
msgs += [session.read_eager().decode('ascii')]
if msgs[-1] == '':
break
>>> print(''.join(msgs))
session.close()