Welcome, guest | Sign In | My Account | Store | Cart

A server program that listens to a client program for logins and inserts the info into a MySQL database. The login info is sent to the server during the login by a editing the /etc/profile.

Python, 146 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#!/usr/bin/python

############## Listenserver  Program 1 ################

import socket
import MySQLdb


class Server:


''' change your database parameters  '''
######################################## Create a default connection #####################################

    def createDefCon(self):

                try:
                        host = "127.0.0.1"
                        port = 3306         ### default mysql port, change if you know better
                        user = "krisk"      ### def parameters
                        passwd = "kish"     ### def parameters
                        db = "loginfo"      ### connection.user_info contains the autho users

                        ### Create a connection object, use it to create a cursor

                        con = MySQLdb.connect(host = host  ,port = port , user = user,passwd = passwd ,db = db)
                        return con ### returns a connection object

                except: 
                        return 0;



####################################### Test connection #######################################################



    def __init__(self, port):
        "Binds the server to the given port."

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(port)

        #Queue up to five requests before turning clients away.
        self.socket.listen(5)
	
	
    def run(self):
        "Handles incoming requests forever."
        con = self.createDefCon()
        cursor = con.cursor()
        
        while True:
            request, client_address = self.socket.accept()
            
            #Turn the incoming and outgoing connections into files.
        
            input = request.makefile('rb', 0)
            output = request.makefile('wb', 0)
            try:
    
                     l = input.readline().strip()
		     print l
		     sql='''insert into  log_info(`ip`,`uname`) values('%s','%s');''' % (client_address[0],l  )
		     print sql
		     cursor.execute(sql);
		      	
                     request.shutdown(2) #Shut down both reads and writes.
            
             except socket.error:
    	             #Most likely the client disconnected.
                     sys.exit(1)

if __name__ == '__main__':

    import sys
    if len(sys.argv) < 3:
        print 'Usage: %s [hostname] [port number]' % sys.argv[0]
        sys.exit(1)
    hostname = sys.argv[1]
    port = int(sys.argv[2])
    Server((hostname, port)).run()



################## TellServer  Program 2 #######################
#!/usr/bin/python


import socket



class Client:



        "A client for the mirror server."
        def __init__(self, server, port):
            "Connect to the given mirror server."
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((server, port))
       
        def mirror(self, s):
        	    "Sends the given string to the server, and prints the response."
        	    self.socket.send(s)


        def close(self):
    	    self.socket.send('\r\n') #We don't want to mirror anything else.
    	    self.socket.close()

if __name__ == '__main__':



    import sys


    if len(sys.argv) < 4:
        print 'Usage: %s [host] [port] [text to be mirrored]' % sys.argv[0]
        sys.exit(1)

    hostname = sys.argv[1]
    port = int(sys.argv[2])

    toMirror = sys.argv[3]
    
    m = Client(hostname, port)
    m.mirror(toMirror)
    m.close()



##################### Infogather Script 1 ###########################
##!/bin/bash

##This program tells the server about the login
## It carries the timestamp and the user info


## change the localhost to the address of your server and the port as it may be
## the case

#python /usr/bin/infosendingclient.py localhost 2000 $USER 

Use of the system

Hack to monitor the user logins at linux boxes in a network.

Database schema

| Field | Type | Null | Key | Default | Extra |

| sno | int(11) | NO | PRI | NULL | auto_increment | | ip | varchar(17) | YES | | NULL | | | uname | varchar(10) | YES | | NULL | | | wh | timestamp | NO | | CURRENT_TIMESTAMP | |

2 comments

Aaron Gallagher 15 years, 4 months ago  # | flag

This is some pretty bad code. Not only is it inconsistently formatted, but your actual python has some problems.

You use a blanket 'except' to ignore all exceptions seemingly to fail silently if there was a problem with the database connection, without trying to catch the specific exception, or even just exceptions that MySQLdb raises. You do the same thing with the client connection, shutting down the server if there are any errors instead of examining the errno and/or closing only that client connection. You don't use DB-API placeholders, so your code is totally vulnerable to SQL injection. You don't use socket.close to close the connection in the server. You limit yourself to only one client connection at a time because you block waiting for the one client to send a line of data before you do anything. This means that one person could intentionally block up your server from allowing anyone else to connect and log in.

Of all that, the SQL injection is probably the worst offense.

Kish (author) 15 years, 2 months ago  # | flag

Thank you for your patient comment. I know I have a long way to go, thanks again for pointing it out.

Will make it better.

:-) Cheers

Created by Kish on Wed, 26 Nov 2008 (MIT)
Python recipes (4591)
Kish's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks