Let us define a function that will take a user's login credentials from the Command Prompt and connect to a telnet server.
Upon successful connection, it will send the Unix 'ls' command. Then, it will display the output of the command, for example, listing the contents of a directory.
Listing 6.1 shows the code for a telnet session that executes a Unix command remotely as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 6 # This program is optimized for Python 3.5.2. # It may run on any other version with/without modifications. # To make it run on Python 2.7.x, needs some changes due to API differences. # Follow the comments inline to make the program work with Python 2. import getpass import sys import telnetlib HOST = "localhost" def run_telnet_session(): user = input("Enter your remote account: ") # Comment out the above line and uncomment
the below line for Python 2.7. # user = raw_input("Enter your remote account: ") password = getpass.getpass() session = telnetlib.Telnet(HOST) session.read_until(b"login: ") session.write(user.encode('ascii') + b" ") if password: session.read_until(b"Password: ") session.write(password.encode('ascii') + b" ") session.write(b"ls ") session.write(b"exit ") print (session.read_all()) if __name__ == '__main__': run_telnet_session()
If you run a telnet server on your local machine and run this code, it will ask you for your remote user account and password. The following output shows a telnet session executed on an Ubuntu machine:
$ python 16_1_execute_remote_telnet_cmd.py Enter your remote account: pradeeban Password: ls exit Last login: Tue Jun 6 22:39:44 CEST 2017 from localhost on pts/20 Welcome to Ubuntu 16.04.2 LTS (GNU/Linux 4.8.0-53-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage 89 packages can be updated. 3 updates are security updates. pradeeban@llovizna:~$ ls INESC-ID GSD openflow Desktop MEOCloud software Documents Downloads Dropbox Obidos floodlight OpenDaylight pradeeban@llovizna:~$ exit logout