Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

Perl : scan a list of networks, looking for hosts responding on the port 80 (http)

// Input : a list of address of routers, in dotted decimal notation
use strict;
use Net::Ping;
use IO::Socket::INET;

sub isodate() {
        my ($day, $mon, $year, $hour, $min, $sec) = (localtime)[3, 4, 5, 2, 1, 0];
        $mon++; # 0-based index
        $year = $year + 1900;
        my $date = sprintf ("%04i-%02i-%02i %02i\:%02i\:%02i", $year, $mon, $day, $hour, $min, $sec);
        return $date;
}

sub testhost {
       my $p = new Net::Ping("tcp");
       $p->{port_num}=80; 
       my @result = $p -> ping($_[0],2);
       return $result[0];
       }

sub to_dot {
	my $n = shift;
	my @decimal;
	for (1..4) {
		unshift @decimal, $n & 0xFF;
		$n >>= 8;
	}
	return join(".",@decimal);
}

my %dejavu;
open FH,"liste.txt";
while (<FH>) {
	chomp;
	my ($routeur,$mask)=split;
	
	next if $routeur !~ /\d+\.\d+\.\d+\.\d+$/ or $mask !~ /\d+\.\d+\.\d+\.\d+$/;
	
	next if defined($dejavu{$routeur});
	$dejavu{$routeur}=1;
	
	my ($o1,$o2,$o3,$o4) = split /\./,$mask;
	my $mask=$o1*256**3+$o2*256**2+$o3*256+$o4;
	my $num = $mask ^ 0xFFFFFFFF;
	$num--;

	my ($o1,$o2,$o3,$o4) = split /\./,$routeur;
	my $net=$o1*256**3+$o2*256**2+$o3*256+$o4 & $mask;
	
	#print join("|",$routeur,&to_dot($net),$num)."\n";
	
	print "Starting scanning network ".to_dot($net).", router = ".$routeur."\n";
	print "Adresses demarrant de ".to_dot($net+1)." et finissant a ".to_dot($net+$num).".\n";
	for my $i (1..$num) {
		my $host=to_dot($net+$i);
		if ( &testhost($host) ) {
			print "$host is alive\n";
			my $port=80;
			my $sock = new IO::Socket::INET (PeerAddr => $host,
					     PeerPort => $port,
					     Proto => 'tcp');
			if ($sock){
				close $sock;
				print "$port -open on $host\n";
				open OUT,">>webservers.txt";
				print OUT join("|",isodate(),$host,to_dot($net),$routeur)."\n";
				close OUT;
			}	else	{
				print "$port -closed on $host\n";
			}

		} else {
			print "$host is not responding\n";
		}
	}
}


close FH;

Send custom UDP packets in Ruby


From: http://www.ruby-forum.com/topic/124159
Author: Bill Kelly

For yet another nifty UDP snippet see Skype-Style Firewall Busting with Ruby and UDP.



require 'socket'

#abort "Usage: server_addr, server_port, cmd_str" unless ARGV.length == 3

UDP_RECV_TIMEOUT = 3  # seconds

def q2cmd(server_addr, server_port, cmd_str)
  resp, sock = nil, nil
  begin
   cmd = "\377\377\377\377#{cmd_str}\0"
    sock = UDPSocket.open
    sock.send(cmd, 0, server_addr, server_port)
    resp = if select([sock], nil, nil, UDP_RECV_TIMEOUT)
      sock.recvfrom(65536)
    end
    if resp
      resp[0] = resp[0][4..-1]  # trim leading 0xffffffff
    end
  rescue IOError, SystemCallError
  ensure
    sock.close if sock
  end
  resp ? resp[0] : nil
end

# your firewall has to allow communication with IP address 67.19.248.74 (port 27912)
#server, port, cmd = *ARGV
server = "tastyspleen.net"
port = 27912
cmd = "status"

result = q2cmd(server, port, cmd)
puts result


J2ME - getIPdevice

// Retrevie IP device

package org.socketdemo;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class SocketDEMO extends MIDlet implements CommandListener
{
	protected SocketDEMO midlet = this;
	
	private Alert info;
	
	protected void destroyApp(boolean value) throws MIDletStateChangeException
	{
		notifyDestroyed();
	}

	protected void pauseApp()
	{

	}

	protected void startApp() throws MIDletStateChangeException
	{
		new Thread()
		{
			public void run()
			{
				SocketConnection socket = null;
				
				try
				{
					socket = (SocketConnection) Connector.open("socket://193.204.114.233:13");
					
					socket.openInputStream();
					
					info = new Alert("Info", "Current IP: " + socket.getLocalAddress() + "\nPort: " + socket.getLocalPort(), null, AlertType.INFO);
					info.setTimeout(Alert.FOREVER);
					info.setCommandListener(midlet);
					
					getDisplay().setCurrent(info);
				}
				catch(Exception error)
				{
					info = new Alert("Info", "Current IP: N/A\nPort: N/A", null, AlertType.INFO);
					info.setTimeout(Alert.FOREVER);
					info.setCommandListener(midlet);
					
					getDisplay().setCurrent(info);
				}
				finally
				{
					if(socket != null)
					{
						try
						{
							socket.close();
						}
						catch(Exception error)
						{
							
						}
					}
				}
			}
		}.start();
	}
	
	protected Display getDisplay()
	{
		return Display.getDisplay(this);
	}

	public void commandAction(Command cmd, Displayable dsp)
	{
		if(cmd == Alert.DISMISS_COMMAND)
		{
			try
			{
				destroyApp(true);
			}
			catch(MIDletStateChangeException error)
			{
			
			}
		}
	}
}

PyS60 - BabelFish

// Translate from language A to language B
// code not complete but it works

import urllib

####################################################################################### <BabelFish>
class BabelFish(object):
    
    def translate(self, lang, message):
        
        try:
            url = urllib.URLopener()
        
            query = urllib.urlencode({
                                      'doit':'done',
                                      'intl':'1',
                                      'lp':lang,
                                      'tt':'urltext',
                                      'urltext':message
                                      })
        
            responde = url.open('http://babelfish.altavista.com/tr', query).read()
        
            start = responde.find('<div style=padding:10px;>') + 25
            stop = responde.find('</div>', start)
        
            return responde[start:stop]
        
        except Exception, error:
            return '-' + str(error)
####################################################################################### </BabelFish>

####################################################################################### <BabelFishUI>
from graphics import *

import appuifw
import e32

class BabelFishUI(object):
    
    def __init__(self):
        
        self.__lock = e32.Ao_lock()
        self.__img = Image.new((176, 144))
        self.__language = 'it_en'
        self.__textUI = None
        
        appuifw.app.exit_key_handler = lambda:self.__lock.signal()
        
        appuifw.app.title = u'BabelFish v1.0'
        appuifw.app.body = self.__canvas = appuifw.Canvas(redraw_callback=self.updateScreen)
        
        appuifw.app.menu = [(u'Translate', lambda:self.__translateUI()), (u'About', lambda:appuifw.note(u'BabelFish: v1.0", "Created by\nWhite Tiger\n<Z-TEAM@Libero.it>', 'info')), (u'Exit', lambda:self.__lock.signal)]
        
        self.updateScreen(None)
        
        self.__menuMain = appuifw.app.menu
        self.__bgMain = appuifw.app.body
        
        self.__lock.wait()
    
    def updateScreen(self, rect):
        
        self.__canvas.blit(self.__img)
    
    def __back(self):
        
        appuifw.app.menu = self.__menuMain
        appuifw.app.body = self.__bgMain
        
        appuifw.app.set_tabs([u'Back'], lambda x:None)
    
    def __translateUI(self):
        
        self.__textUI = appuifw.Text()
                
        appuifw.app.menu = [(u'Translate', lambda:self.__translate()), (u'Language', lambda:self.__setLanguage()), (u'Clear', lambda:self.__textUI.clear()), (u'Back', lambda:self.__back())]
                   
        appuifw.app.body = self.__textUI
                
    def __setLanguage(self):
        
        resp = appuifw.selection_list([u'italiano-inglese', u'inglese-italiano', u'inglese-francese', u'francese-inglese', u'inglese-tedesco', u'tedesco-inglese',
                                       u'francese-italiano', u'italiano-francese'], 1)
        
        if resp == 0:
            self.__language = 'it_en'
        elif resp == 1:
            self.__language = 'en_it'
        elif resp == 2:
            self.__language = 'en_fr'
        elif resp == 3:
            self.__language = 'fr_en'
        elif resp == 4:
            self.__language = 'en_de'
        elif resp == 5:
            self.__language = 'de_en'
        elif resp == 6:
            self.__language = 'fr_it'
        elif resp == 7:
            self.__language = 'it_fr'
            
    def __translate(self):
        
        babel = BabelFish()
        
        resp = babel.translate(self.__language, self.__textUI.get())
        
        if resp[0] == '-':
            self.__textUI.set(unicode(resp[1:]))
        else:
            self.__textUI.set(unicode(': ' +self.__textUI.get() + '\n: ' + resp))
                
        appuifw.note(u'Translate', 'conf')
####################################################################################### </BabelFishUI>

if __name__ == '__main__':
    
    BabelFishUI()

Python - My External IP Address

// My external ip address

import urllib

url = urllib.URLopener()
resp = url.open('http://myip.dk')
html = resp.read(114)

end = html.find("</title>")
start = html.find("IP:") + 3

print html[start:end].strip()

Python - Change user-agent

// Cambiare user-agent con urllib

import urllib

class AppURLopener(urllib.FancyURLopener):

	version = 'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1'

urllib._urlopener = AppURLopener()


// Cambiare user-agent con urllib2

import urllib2

headers = { 'user-agent':'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1',
		    'keep-alive':'300',
		    'content-type':'application/x-www-form-urlencoded'
		  }

setup computer hostname in linux

* edit
/etc/sysconfig/network

* add the following lines:

HOSTNAME=www.test.com
DOMAINNAME=test.com

search with grep in linux


Searching files

grep (r - recursive, s - no messages, n -line number, i - case insensitve, H -with filename)
grep -rsniH your_string

match lines containing the string "I am a cat" or the string "I am a dog".
grep "I am a \(cat\|dog\)" 


Search application

to find PID (process ID) of a certain application or process,
pgrep


find application port
netstat -a | grep ftp

network utils


check port
netstat -l


Download files from the listed file.
wget -i <file> 

Transfer files on windows network

From Fadly Tabrani's recipe.
You need his implementation of netcopy, netmove, netdelete.
pywin32 extension required.
# Copy "c:\documents" folder/file to "c:\transferred" on host "w0001".
netcopy('w0001', 'c:\\documents', 'c:\\transferred')

# Move with account credentials.
netmove('w0001', 'c:\\documents', 'c:\\transferred', 'admin', 'adminpass')

# Delete with another account.
netdelete('w0001', 'c:\\transferred', 'testdom\\user1', 'user1pass')
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS