Simple python servlet (single user connect)

From wiki.network-crawler.de
Jump to: navigation, search

e.g. for the use with nc (netcat). Available for every OS.

#!/usr/bin/python

from socket import *
import string
import time
import os
import sys
from subprocess import call

script = "/svn/trunk/CodesysSpV3/Platforms/Linux/Projects/3s_delivery_build.sh"

# create a socket of the basic type.
s = socket(AF_INET, SOCK_STREAM)

senddata1 = "Linux build server remote mechanism, Version 0.1c now ready for input (try help for some examples)\n"

HOST = "192.168.100.10"
PORT = 42

s.bind((HOST, PORT))
s.listen(1)

helpstring = "Example:\nprepare rts /svn/test tags V3.3.0.10\n" + \
"prepare rts /svn/test trunk\n" + \
"prepare rts /svn/test branches CurrentDeliveryVersion_V3.3\n" + \
"build rts /svn/test/trunk/ trunk default ppc trunk/\n" + \
"build rts /svn/test/tags/V3.3.0.10/ 3.3.0.10 default ppc 3.3.0.10/\n" + \
"build rts /svn/test/branches/CurrentDeliveryVersion_V3.3/ current default ppc current/\n"

mystdout = os.dup(1)
mystderr = os.dup(2)

print "Server started\n"

while 1:
	(incomingsocket, address) = s.accept()
	incomingsocket.send(senddata1)

	straddress = str(address)
	testlist = string.split(straddress, ",")
	gethost = string.split(testlist[0], "'")
	getaddr = string.split(testlist[1], ")")
	host = gethost[1]
	incomingport = int(getaddr[0])

	senddata2 = "Build request from [" + host +"] now processed... Thank you!\n" 

	print "Connection attempt on port", PORT, "from", host, ":", incomingport

	data = incomingsocket.recv(1024)

	print data
	if data == "update\n":
		senddata2 = "Not implemented yet!\n"
	elif data == "help\n":
		senddata2 = helpstring
	elif data == "\n":
		senddata2 = "no empty commands allowed"
	else:
		arglist = string.split(data, " ");

		os.dup2(incomingsocket.fileno(), 1)
		os.dup2(incomingsocket.fileno(), 2)

		os.setgid(100)
		os.setuid(1000)
		os.umask(007)
		
		if arglist.__len__() > 1:
			prepath = "/usr/remotebuild/"
			basepath = prepath + arglist[2] + '/'
			
			if arglist[0] == "build":
				if arglist[1] == "rts":
					buildprofile = arglist[5] + '_' + arglist[4] + ".build"
					call([script, basepath, arglist[3], buildprofile, arglist[5], arglist[6]]);
				if arglist[1] == "plchandler":
					print "not implemented yet!\n"
			if arglist[0] == "prepare":
				if arglist[1] == "rts":
					paramscnt = arglist.__len__();
					if paramscnt == 4:
						call([script, basepath, arglist[3], arglist[0]]);
					else:
						call([script, basepath, arglist[4], arglist[0], arglist[3]]);
				if arglist[1] == "plchandler":
					print "not implemented yet!\n"
		else:
			senddata2 = "invalid argument, closing connection...\n"
		os.dup2(mystdout, 1)
		os.dup2(mystderr, 2)

	incomingsocket.send(senddata2)

	incomingsocket.close()
	print "Connection closed on port", PORT, "from", host, ":", incomingport