Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old December 11th, 2012, 02:36 PM
bilboPYT bilboPYT is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 bilboPYT User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 18 m 41 sec
Reputation Power: 0
Netstat detect number of connection on port

I have no clue how to code but I need to modify the below script if found on xbmc forums. The script scans for connections on certain ports and aborts the shutdown process if present.

I want modify it so it only aborts if there are three or more instances of port 9982 and that all. Can someone help? thanks.

Code:
#!/usr/bin/python
from __future__ import print_function

import xbmc
import subprocess

# Set of (protocol, local port) tuples.
watched = {
    ('tcp', 22), # SSH
    ('tcp', 445), # samba
    }
sleep_time = 60 * 1000 # sleep time between checks in miliseconds

def log(msg):
    print("service.inhibit_shutdown: {}".format(msg))

def check_services():
    """ Check if any of the watched services is running. """

    netstat = subprocess.check_output(['/bin/netstat', '--protocol=inet', '-n'], universal_newlines=True)

    for line in netstat.split('\n')[2:]:
        items = line.split()
        if len(items) < 4:
            continue

        proto = items[0]
        port = int(items[3].split(':')[-1])

        if (proto, port) in watched:
            log("Found {} connection from {} to port {}".format(proto, items[4], port))
            return True

    log("No connection found.")
    return False

while not xbmc.abortRequested:
    if check_services():
        xbmc.executebuiltin('InhibitIdleShutdown(true)')
    else:
        xbmc.executebuiltin('InhibitIdleShutdown(false)')
    xbmc.sleep(sleep_time)

Reply With Quote
  #2  
Old December 14th, 2012, 04:21 AM
Quackajack Quackajack is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2012
Posts: 39 Quackajack User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 10 h 49 m 43 sec
Reputation Power: 1
Change the watched protocols to the one you want (I've assumed it is a tcp not a udp protocol) as follows:
Code:
watched = { ('tcp', 9982) }


Then change the check services function:
Code:
def check_services():
    # description and netstat line as before
    count = 0

    for line in netstat.split('\n')[2:]:
        # next 5 lines as before

        if (proto, port) in watched:
            count += 1
            log("Found {} connection number {} from {} to port {}".format(proto, count, items[4], port))
            if count >= 3:
                return True

    if count == 0:
        log("No connection found.")
    return False

Reply With Quote
  #3  
Old December 16th, 2012, 06:48 AM
bilboPYT bilboPYT is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Dec 2012
Posts: 2 bilboPYT User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 18 m 41 sec
Reputation Power: 0
Many thanks

Code:
#!/usr/bin/python
from __future__ import print_function

import xbmc
import subprocess

# Set of (protocol, local port) tuples.
watched = { ('tcp', 9982), }
sleep_time = 60 * 1000 # sleep time between checks in miliseconds

def log(msg):
    print("service.inhibit_shutdown: {}".format(msg))

def check_services():
    """ Check if any of the watched services is running. """

    netstat = subprocess.check_output(['/bin/netstat', '--protocol=inet', '-n'], universal_newlines=True)

count=0

    for line in netstat.split('\n')[2:]:
        items = line.split()
        if len(items) < 4:
            continue

        proto = items[0]
        port = int(items[3].split(':')[-1])

               if (proto, port) in watched:
            count += 1
            log("Found {} connection number {} from {} to port {}".format(proto, count, items[4], port))
            if count >= 3:
                return True

    if count == 0:
        log("No connection found.")
    return False

while not xbmc.abortRequested:
    if check_services():
        xbmc.executebuiltin('InhibitIdleShutdown(true)')
    else:
        xbmc.executebuiltin('InhibitIdleShutdown(false)')
    xbmc.sleep(sleep_time))


is giving an error:

Error Contents: ('unexpected indent', ('/home/billy/.xbmc/addons/service.inhibit_shutdown/inhibit_shutdown.py', 21, 4, " for line in netstat.split('\\n')[2:]:\n"))
IndentationError: ('unexpected indent', ('/home/billy/.xbmc/addons/service.inhibit_shutdown/inhibit_shutdown.py', 21, 4, " for line in netstat.split('\\n')[2:]:\n"))

edit: i redid the spaces in notepad and it seems have loaded okay now.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Netstat detect number of connection on port

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap