#!/usr/bin/env python
# Simple finger client -- uses basic socket operations

import sys
from socket import * # So I don't have to prefix with "socket"
import string
FINGERPORT = 79 # standard port for finger

def finger(user, machine, port=FINGERPORT):
    # create a socket and connect to port on machine
    s = socket(AF_INET, SOCK_STREAM)
    s.connect((machine, port))

    # send the user name
    s.send(user+"\r\n")

    # collect data until server closes the connection
    # Note: This _should_ have some size limit.
    alldata = [] # This will be a list of chunks received
    while True:
       data = s.recv(1024)
       if not data: break
       alldata.append(data)
    s.close()

    # Concatenate all of the chunks together.
    return string.join(alldata)

def main():
    try:
        user_machine = sys.argv[1]
        user, machine = string.splitfields(user_machine, "@")
        if len(sys.argv)>2:
           port = int(sys.argv[2])
        else:
           port = FINGERPORT
    except:
        print "Usage: finger.py user@machine [port_number]"
        raise SystemExit

    print finger(user, machine, port)

if __name__=="__main__": main()
