Why does pager not opening with less command?

Viewed 36

I am running this python script to execute a command and connect it's input and output to a client on the port.

import getpass
import socket
import subprocess
username = getpass.getuser()
host = socket.gethostbyname('')
port = 443
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection = None
while connection is None:
    try:
        connection = s.connect((host, port))
        s.send("[+] We are connected to %s" % username)
        while True:
            try:
                exec_code = s.recv(1024)
                if exec_code == "quit":
                    break
                else:
                    print "1"
                    proc = subprocess.Popen("less data.txt", shell=True, stdout=s, stdin=s)
                    proc.wait()

                    print "2"
            except Exception, err:
                print err
    except Exception, e:
        print e
s.close()

The problem I am facing is that less command prints output on the client side but does not opens a pager. Any ideas on how to resolve this thing.

1 Answers

The problem is the program less does not use stdin and stdout as plain streams. The less is a terminal program and uses terminfo or termcap to control the terminal get terminal capabilities. When the python program executes the less then its stdout and stdin are not bound to any terminal but to a socket. The less has no chance to get terminal size for example so it cannot execute paging. It similar to situation when you call these trivial commands:

less data.txt
less data.txt | cat

The former command does paging. The later command just prints the file to stdout because the stdout of the less is not a terminal but a pipe and less cannot do paging.

When the paging is required on the server side then the server should implement paging.

Related