And Python (was: client <-> server interaction in C

Roger Merchberger zmerch at 30below.com
Tue Nov 22 10:34:50 PST 2005


Rumor has it that Gerard Beekmans may have mentioned these words:
>Attached server.c and client.c.

Time for me to ping in here:

I'm awfully bad at C - been learning it for 20 years, and never quite seem 
to get the hang of it, mainly because I become disgusted at it, then write 
what I need Python in 1/5 the time... and no segfaults! I was weaned on 
Basic & Assembly, so maybe that's just a product of my upbringing. [[ That, 
and my first computer with a C compiler on it took almost 10 minutes to 
compile "Hello World" until I could afford a RAMdisk. Ever *swap floppies* 
just to compile a 4-line program? It ain't fun. ]]

I used to be OK in Perl, but never did sockets [[ or anything decently 
"high-level" with it ]] and I've not used it since I learned Python, so I'm 
pretty rusty with it as well, but I could prolly relearn it.

I needed to write a client-server program recently (to xfer some MRTG info 
from a server that wasn't running any webservices whatsoever to the 
webserver), and so I chose Python -- this is what I came up with. It took 
me a couple of hours to make it work, having never programmed anything 
sockets-based before, I don't think that's *too* bad... [[ Ow! I just hurt 
my arm!!! ;-) ]]  Googling helped a lot, tho. ;-)

Anyway, the first program is the server - it sits & waits on port 9191, and 
when it receives information in the form of:

"string" --> filename to write
number
number
number
number   --> 4 lines of numeric info for MRTG

it writes that info in the specified filename.

Here's the server:

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

[root at www bin]# more qmail_mrtg_daemon.py

#!/usr/bin/python

def daemonize():
   """Become a Linux/UNIX daemon"""
   import os,sys
   os.chdir('/')
   if os.fork(): os._exit(0)
   os.setsid()
   sys.stdin  = sys.__stdin__  = open('/dev/null','r')
   sys.stdout = sys.__stdout__ = open('/dev/null','w')
   sys.stdout = sys.__stderr__ = os.dup(sys.stdout.fileno())

def daemonize_log_demo():
   """Demonstrate deamonize() with trivial syslog output"""
   import time,syslog,os
   log = syslog.openlog("ZDaemon[%d]" % os.getpid())
   t=0
   while 1:
     t+=1
     syslog.syslog(syslog.LOG_INFO,"Interval %d  reached" % (t) )
     time.sleep(5)

if __name__=='__main__':
   daemonize()
#  daemonize_log_demo()

   qq = []

   import socket

#   print "#create an INET, STREAMing socket"

  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#   print "#bind the socket to a public host, and a well-known port"

  s.bind((socket.gethostname(), 9191))

#   print "#become a server socket"

  while 1:

    s.listen(1)

    conn, addr = s.accept()

#   print "Now we start accepting info..."
#   print "=-=-=-=-=-=-=-=-=-=-=-=-=-=-="

    while 1:
      zz = conn.recv(1024)
      if not zz:  break

#       if not (addr[0] == '12.15.88.1' or addr[0] == '12.15.88.237'):  break
      if not (addr[0] == '12.15.88.1' or addr[0] == '12.2.85.9' or addr[0] 
== '12.15.88.237'):  brea
k

#      print "%s - %s: %s" % (conn,addr,zz)
      qq = zz.split('\n')
#      print len(qq)
      outfile = open('/etc/mrtg/%s' % qq[0],'w')
      for i in range(1,len(qq)):
        outfile.write(qq[i])
        outfile.write('\n')

      outfile.close()

    conn.close()

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Here's the client that sends the system info over to the server:

[root at mail root]# more /usr/local/bin/send_mrtg.py
#!/usr/bin/python

import socket, os, sys
from time import sleep

#  Go get the uptime from the mailserver...

uptime_s = os.popen("uptime").readlines()[0]

uptime = uptime_s.split(' ')[-3:]
uptime_5 = int(float(uptime[0].replace(',',''))*100)
uptime_15 = int(float(uptime[2].replace('\n',''))*100)

#  Go get the info to send to the mailserver...

ext_s = os.popen("grep 'www.spamhaus.org' < /var/log/qmail/smtpd/current|wc 
-l").readlines()
ext_sbl = int(ext_s[0])

ext_o = os.popen("grep 'ORDB' < /var/log/qmail/smtpd/current|wc 
-l").readlines()
ext_openrelay = int(ext_o[0])

allday_spamhaus_b = os.popen("grep 'www.spamhaus.org' 
/var/log/qmail/smtpd/current /var/log/qmail/sm
tpd/\@40* |wc -l").readlines()
int_allday_spamhaus = int(allday_spamhaus_b[0])

allday_ordb_b = os.popen("grep 'ORDB' /var/log/qmail/smtpd/current 
/var/log/qmail/smtpd/\@40* |wc -l
").readlines()
int_allday_ordb = int(allday_ordb_b[0])

ext_a = os.popen("grep 'abuseat' < /var/log/qmail/smtpd/current|wc 
-l").readlines()
ext_abuseat = int(ext_a[0])

int_t = os.popen("grep 'bad SMTP server bounces' < 
/var/log/qmail/smtpd/current|wc -l").readlines()

int_tcpsmtp = int(int_t[0])

int_b = os.popen("grep 'badhelo' < /var/log/qmail/smtpd/current|wc 
-l").readlines()

int_badhelo = int(int_b[0])

allday_badhelo_b = os.popen("grep 'badhelo' /var/log/qmail/smtpd/current 
/var/log/qmail/smtpd/\@40*
|wc -l").readlines()
int_allday_badhelo = int(allday_badhelo_b[0])

allday_badsmtp_b = os.popen("grep 'bad SMTP server bounces' 
/var/log/qmail/smtpd/current /var/log/qm
ail/smtpd/\@40* |wc -l").readlines()
int_allday_badsmtp = int(allday_badsmtp_b[0])

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('external_spam.txt\n%i\n%i\n\n' % (ext_sbl,ext_openrelay))
s.close()

sleep(0.2)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('internal_spam.txt\n%i\n%i\n\n' % (int_tcpsmtp,int_badhelo))
s.close()

sleep(0.2)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('abuseat_spam.txt\n%i\n%i\n\n' % (ext_abuseat,0))
s.close()

sleep(0.2)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('mail_uptime.txt\n%i\n%i\n\n' % (uptime_5,uptime_15))
s.close()

sleep(0.2)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('allday_internalspam.txt\n%i\n%i\n\n' % 
(int_allday_badhelo,int_allday_badsmtp))
s.close()

sleep(0.2)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('12.15.88.2',9191))
s.send('allday_externalspam.txt\n%i\n%i\n\n' % 
(int_allday_spamhaus,int_allday_ordb))
s.close()

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

Not really intended to say much - just thought I'd "share with the group." ;-)

I apologize for the line-wrapping; never really thought I'd be emailing 
these things... ;-)

HTH,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger   | "Profile, don't speculate."
SysAdmin, Iceberg Computers |     Daniel J. Bernstein
zmerch at 30below.com          |




More information about the alfs-discuss mailing list