Skip to content

Instantly share code, notes, and snippets.

@elimence
Created May 23, 2013 12:04
Show Gist options
  • Save elimence/5635608 to your computer and use it in GitHub Desktop.
Save elimence/5635608 to your computer and use it in GitHub Desktop.
This piece of code is used to terminate programs running on any port This is version 1.0 and so it doesn't do much besides this. More functionality will be added at a later date A lot of the code is unnecessary and is just there for fancy output Such code will be eliminated in version 2.0
#!/usr/bin/env python
import re
import sys
import shlex
import subprocess
from time import sleep
def main(port):
port = port[0]
visualize('scanning port %s' % port)
msg1 = 'Successfully terminated %s - PID %s - on Port %s'
msg2 = 'No Process is Listening On Port %s'
#try:
command = 'sudo netstat -tulpn | grep :%s' %(port)
#proc_obj = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) # I can't bring myself to delete this line of code :)
# examples of beautiful code that don't work
try:
proc_str = subprocess.check_output(command, shell=True)
#proc_str = proc_obj.communicate()[0]
proc_inf = get_proc_inf(proc_str)
# print proc_inf[1]
stream(' : Found 1 <%s>' %(proc_inf[1]))
print ''
sleep(1)
visualize('Searching for %s PID \n' %(proc_inf[1]))
stream(' : Found <PID=%s>' %(proc_inf[0]))
print ''
sleep(1)
status = terminate(proc_inf[0])
visualize('Sending kill signal to %s - PID: %s \n' %(proc_inf[1], proc_inf[0]))
stream(' : OK')
print ''
print ''
sleep(1)
print msg1 % (proc_inf[1], proc_inf[0], port)
except subprocess.CalledProcessError, e:
print e.message
print msg2 % (port)
except Exception, e:
print e.message
print 'Unhandled Exception, Go down on your knees and pray ..... '
finally:
cleanup()
#DONE
# CALLED FUNCTIONS
def get_proc_inf(str):
proc_str = str.strip()
proc_list = proc_str.split('\n')
# You may think the ff lines could be less redundant, but hey! my grandma thinks so too
if len(proc_list) > 2:
for proc in proc_list:
match = re.search(r'(\d{4,8})/(\w*)$', proc)
if match:
return match.group(1), match.group(2)
else:
match = re.search(r'(\d{4,8})/(\w*)$', proc_str)
if match:
return match.group(1), match.group(2)
def terminate(proc_id):
command = 'sudo kill -1 %d' %(int(proc_id))
status = subprocess.check_output(command, shell=True)
return status
def cleanup ():
print 'Cleaning up : '
for i in range(0,101):
sys.stdout.write("\r%d %s" % (i,'%'))
# sys.stdout.write(i)
sys.stdout.flush()
sleep(0.1)
print ''
print 'PROCESS COMPLETE !1'
sys.stdout.close()
# print ''
def visualize (str):
print ''
stream('%s' %(str))
for i in range(20):
stream('.')
sleep(0.2)
def stream(s):
sys.stdout.write(s)
sys.stdout.flush()
if __name__ == '__main__':
try:
main(sys.stdin.readlines())
except Exception, e:
main(sys.argv[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment