MIRC Port Scanner - python

if data.find('!scan') != -1:
nick = data.split('!')[ 0 ].replace(':','')
targetip = str(socket.gethostbyname(args))
sck.send('PRIVMSG ' + chan + " :" ' scanning host' + " " + targetip + '\r\n')
for i in range(20, 1025):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex((targetip, i))
if (result == 0) :
s.send('PRIVMSG ' + chan + " :" 'port %d: OPEN' % (i,) + '\r\n')
s.close()
The script works, but it ping timeout before it can get an open port, how can I make it so it can scan a few ports then check for a ping from the server and send a pong then scan a few more ports so that it wont ping timeout.

The best solution is to use multiple threads, with the main thread parsing input from IRC and responding to PINGs, while other threads do actual command processing and anything that could take a long time.
skybot, my IRC bot, spawns a new thread whenever a command is issued, and uses thread-safe queues to pass messages between them.

Related

Sending Client Data With a Timer

So I have a simple Client-Server.
They properly connect with command line arguments, send and receiving data.
When the server isn't up and running but the client executes: Attempt to connect, after 1 second display message that it timed out (3 times) before closing.
the closest i can come to it, is simply attempting it 3 times.
import sys
from socket import *
# Get the server hostname, port and data length as command line arguments
argv = sys.argv
host = argv[1]
port = argv[2]
count = argv[3]
# Command line argument is a string, change the port and count into integer
port = int(port)
count = int(count)
data = 'X' * count # Initialize data to be sent
# Create UDP client socket. Note the use of SOCK_DGRAM
clientsocket = socket(AF_INET, SOCK_DGRAM)
# Sending data to server
# times out after 1 second (?)
for i in range(3):
try:
print("Sending data to " + host + ", " + str(port) + ": " + data)
clientsocket.sendto(data.encode(),(host, port))
# Receive the server response
dataEcho, address = clientsocket.recvfrom(count)
# Display the server response as an output
print("Receive data from " + address[0] + ", " + str(address[1]) + ": " + dataEcho.decode())
break
except:
print("timed out")
finally:
#Close the client socket
clientsocket.close()
How would I add a timer to it? Just adding 1 second between each attempt instead of how I coded.
If you just want the program to sleep for x seconds you could import time, and then add time.sleep(num_of_seconds_to_sleep) after your clientsocket.close() line.

Twisted multiple peers

I'm currently working with twisted in python and I'm trying to make a multicast between many peers(each of them can send and receive messages, send acks etc). My main looks like this :
if __name__ == '__main__':
serial_process_num, address = parse_args()
if serial_process_num == '0':
factory = PeerFactory('0', 'log')
reactor.listenTCP(address[1], factory)
reactor.listenTCP(address[1]+1, factory)
print "Process 0 is listening #" + address[0] + " port " + str(address[1])
print "Process 0 is listening #" + address[0] + " port " + str(address[1]+1)
elif serial_process_num == '1':
factory = PeerFactory('1', '')
host, port = address
print "Connecting to process 0 " + host + " port " + str(port)
reactor.connectTCP(host, port, factory)
print "Process 1 is listening #" + address[0] + " port " + str(address[1]+2)
reactor.listenTCP(port+2, factory)
else:
factory = PeerFactory('2', '')
host, port = address
print "Connecting to process 0 " + host + " port " + str(port+1)
reactor.connectTCP(host, port+1, factory)
print "Connecting to process 1 " + host + " port " + str(port+2)
reactor.connectTCP(host, port+2, factory)
reactor.run()
I kept this one simple because I want to understand my mistake, so im using only 3 peers.I start the first one with serial_process_num 0 from the cmd (ex py example.py 0), then the 1 and 2.Am I setting up the listeners/connecttcp correctly? Whenever I send messages between those 3, I only receive half of them in every peer. (i use self.transport.write('example')
Is there an alternative way to multicast through TCPconnect in twisted?(im following krondos tutorial) and how can I make multiple connections between multiple peers with twisted?
Multicast is a datagram protocol, which means that you do not have a stream of bytes in the same way that you do with TCP; in other words, it's a kind of UDP. So no, you cannot use TCP with it, in Twisted or otherwise.

Creating a simple IRC bot in python. Having trouble

So a few hours ago I decided to try my hands on sockets with python and build a simple irc bot. So far I'm having some trouble getting it connected to the server. I get the following erros:
b":irc.ku.cx 439 * :Please wait while we process your connection.\r\n:irc.ku.cx NOTICE AUTH :*** Couldn't look up your hostname (cached)\r\n"
b':irc.ku.cx NOTICE AUTH :*** Checking Ident\r\n'
b':irc.ku.cx NOTICE AUTH :*** No Ident response\r\n'
After that it stalls out. But about a minute of it running I suddenly get an endless amount of b"", each in a new line (probably something to do with the while loop in the code). This is my code:
import socket
server = 'irc.rizon.net'
channel = '#linux'
nick = 'MyBot'
port = 6667
ircsock = socket.socket()
ircsock.connect((server, port))
ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))
while True:
data = ircsock.recv(2048)
print (data)
if data.find(b"PING") != -1:
ircsock.send(b"PONG :" + data.split(':')[1])
Thanks for any help you guys can provide.
As icktoofay said, there are extra quotes in your code. Also, in IRC you need to add a line break (\r\n) to the end of every command.
Replace these lines:
ircsock.send(bytes('"NICK " + nick', 'UTF-8'))
ircsock.send(bytes('"USER " + nick + " " + nick + " " + nick + " :" + nick', 'UTF-8'))
with
ircsock.send(bytes("NICK " + nick + "\r\n", 'UTF-8'))
ircsock.send(bytes("USER " + nick + " " + nick + " " + nick + " :" + nick + "\r\n", 'UTF-8'))
and it should work.
By the way, I recommend using socket.makefile() instead, which handles buffering and encoding for you. Here's your code modified to use the file interface:
import socket
server = 'irc.rizon.net'
channel = '#linux'
nick = 'MyBot'
port = 6667
ircsock = socket.socket()
ircsock.connect((server, port))
handle = ircsock.makefile(mode='rw', buffering=1, encoding='utf-8', newline='\r\n')
print('NICK', nick, file=handle)
print('USER', nick, nick, nick, ':'+nick, file=handle)
for line in handle:
line = line.strip()
print(line)
if "PING" in line:
print("PONG :" + line.split(':')[1], file=handle)
Here, I use the print function which inserts spaces and newlines automatically.

Python: IndexError: list index out of range with IRC Bot

I have been making a Python Twitch IRC Bot and it all works besides one issue. About every 20 mins it will crash with the error:
Traceback (most recent call last):
File "E:\Geekster_Bot\Geekster_Bot Code\Geekster_Bot_Test_Write", line 54, in <module>
user = data.split(':')[1]
IndexError: list index out of range
I have researched this and tried several things. But to not prevail.
I am still very new to python, and done everything i know of. This is the code area containing the issue.
data = irc.recv(1204) #gets output from IRC server
user = data.split(':')[1]
user = user.split('!')[0] #determines the sender of the messages
print data
Its the point the incoming data from the IRC gets split. the ':' is the split because this is what is used in the IRC between the Nickname and IRC Message. But. Even without use, it doesn't crash for around 20 mins. With use, it does the same. No crash until after 20 mins.
Any Ideas?
UPDATE
queue = 0 #sets variable for anti-spam queue functionality
newsmsg = 'whitelist'
irc = socket.socket()
irc.connect((server, 6667)) #connects to the server
#sends variables for connection to twitch chat
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
def queuetimer(): #function for resetting the queue every 30 seconds
global queue
print 'queue reset'
queue = 0
threading.Timer(30,queuetimer).start()
queuetimer()
while True:
def message(msg): #function for sending messages to the IRC chat
global queue
queue = queue + 1
print queue
if queue < 20: #ensures does not send >20 msgs per 30 seconds.
irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n')
else:
print 'Message deleted'
def socialtimer(): #function for announcing social
global ntimer
z = open('E:\mIRC\Twitter.txt')
SOCIAL = z.read()
message (SOCIAL)
print 'Social Timers Started!'
ntimer = threading.Timer(1200,socialtimer)
ntimer.start()
data = irc.recv(1204) #gets output from IRC server
try: user = data.split(':')[1];
except IndexError: print (data)
user = user.split('!')[0] #determines the sender of the messages
print (data)
Below this is code for the commands i use the bot for. This just uses data.find
Ok from what I see, catching that exception is quite natural and shouldn't be harmful. Once every while, there isn't anything new on the server to pull and so data is an empty string. However, a clearer way to do this might be (also, I took liberty of rewriting some of your code and I'm assuming the last block of your code is also inside while True):
#It's good practice to define functions first, too keep definitions in one place
def queuetimer(): #function for resetting the queue every 30 seconds
global queue
print 'queue reset'
queue = 0
threading.Timer(30,queuetimer).start()
def message(msg): #function for sending messages to the IRC chat
global queue
queue = queue + 1
print queue
if queue < 20: #ensures does not send >20 msgs per 30 seconds.
irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n')
else:
print 'Message deleted'
def socialtimer(): #function for announcing social
global ntimer
z = open('E:\mIRC\Twitter.txt')
SOCIAL = z.read()
message (SOCIAL)
print 'Social Timers Started!'
ntimer = threading.Timer(1200,socialtimer)
ntimer.start()
queue = 0 #sets variable for anti-spam queue functionality
newsmsg = 'whitelist'
irc = socket.socket()
irc.connect((server, 6667)) #connects to the server
#sends variables for connection to twitch chat
irc.send('PASS ' + password + '\r\n')
irc.send('USER ' + nick + ' 0 * :' + bot_owner + '\r\n')
irc.send('NICK ' + nick + '\r\n')
irc.send('JOIN ' + channel + '\r\n')
queuetimer()
while True:
data = irc.recv(1024) #gets output from IRC server, 1024 is a better number than 1204
#make sure data isn't an empty string
if data != '':
user = data.split(':')[1]
user = user.split('!')[0] #determines the sender of the messages
print (data)
else:
print ("Nothing to get from the server")
By the way, correct syntax for try...except clause is
try:
#do something
except ExceptionName:
#do something else
else:
#do something if no exceptions occurred
finally:
#do something even if an unhandled exception occurs and then rise it
I simply couldn't fit that in my comment. Link to documentation

Python socket server/client programming

So I am just getting into python and trying out some stuff. To start, I am making a server that does simple stuff like "GET"s stored text, "STORE"s new text over the old stored text, and "TRANSLATE"s lowercase text into uppercase. But I have a few questions. Here is my code so far:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 24069 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
data = conn.recv(1024)
reply = 'OK...' + data
if not data: break
conn.send(data)
conn.close()
s.close()
To start changing text from a client into uppercase, from my other programming knowledge, I assume I'd store the client's text in a variable and then run a function on it to change it to uppercase. Is there such a function in python? Could someone please give me a snippet of how this would look?
And lastly, how would I do something like a GET or STORE in python? My best guess would be:
data = conn.recv(1024)
if data == GET: print text
if data == STORE: text = data #Not sure how to reference the text that the client has entered
Thank you so much for any help! :)
Note to self:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 24069 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(1)
print 'Socket now listening'
# Accept the connection
(conn, addr) = s.accept()
print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1])
storedText = 'Hiya!'
while 1:
data = conn.recv(1024)
tokens = data.split(' ', 1)
command = tokens[0]
if command == 'GET':
print addr[0] + ':' + str(addr[1]) + ' sends GET'
reply = storedText
elif command == 'STORE':
print addr[0] + ':' + str(addr[1]) + ' sends STORE'
storedText = tokens[0]
reply = '200 OK\n' + storedText
elif command == 'TRANSLATE':
print addr[0] + ':' + str(addr[1]) + ' sends TRANSLATE'
storedText = storedText.upper()
reply = storedText
elif command == 'EXIT':
print addr[0] + ':' + str(addr[1]) + ' sends EXIT'
conn.send('200 OK')
break
else:
reply = '400 Command not valid.'
# Send reply
conn.send(reply)
conn.close()
s.close()
I see that you're quite new to Python. You can try to find some code example, and you should also learn how to interpret the error message. The error message will give you the line number where you should look at. You should consider that line or previous line, as the error may be caused by previous mistakes.
Anyway, after your edits, do you still have indentation error?
On your real question, first, the concept.
To run client/server, you'll need two scripts: one as the client and one as the server.
On the server, the script will just need to bind to a socket and listen to that connection, receive data, process the data and then return the result. This is what you've done correctly, except that you just need to process the data before sending response.
For starter, you don't need to include the accept in the while loop, just accept one connection, then stay with it until client closes.
So you might do something like this in the server:
# Accept the connection once (for starter)
(conn, addr) = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
stored_data = ''
while True:
# RECEIVE DATA
data = conn.recv(1024)
# PROCESS DATA
tokens = data.split(' ',1) # Split by space at most once
command = tokens[0] # The first token is the command
if command=='GET': # The client requests the data
reply = stored_data # Return the stored data
elif command=='STORE': # The client want to store data
stored_data = tokens[1] # Get the data as second token, save it
reply = 'OK' # Acknowledge that we have stored the data
elif command=='TRANSLATE': # Client wants to translate
stored_data = stored_data.upper() # Convert to upper case
reply = stored_data # Reply with the converted data
elif command=='QUIT': # Client is done
conn.send('Quit') # Acknowledge
break # Quit the loop
else:
reply = 'Unknown command'
# SEND REPLY
conn.send(reply)
conn.close() # When we are out of the loop, we're done, close
and in the client:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 24069 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
while True:
command = raw_input('Enter your command: ')
if command.split(' ',1)[0]=='STORE':
while True:
additional_text = raw_input()
command = command+'\n'+additional_text
if additional_text=='.':
break
s.send(command)
reply = s.recv(1024)
if reply=='Quit':
break
print reply
Sample run (first run the server, then run the client) on client console:
Enter your command: STORE this is a text
OK
Enter your command: GET
this is a text
Enter your command: TRANSLATE
THIS IS A TEXT
Enter your command: GET
THIS IS A TEXT
Enter your command: QUIT
I hope you can continue from there.
Another important point is that, you're using TCP (socket.SOCK_STREAM), so you can actually retain the connection after accepting it with s.accept(), and you should only close it when you have accomplished the task on that connection (accepting new connection has its overhead). Your current code will only be able to handle single client. But, I think for starter, this is good enough. After you've confident with this, you can try to handle more clients by using threading.

Categories

Resources