Making a module use functions and variables defined within the main program - python

I'm making an IRC bot for my network. To make the code cleaner, I am defining functions in modules. All these modules are in a folder called "plugins". One module say calls the function sendMsg and fails because it's trying to run a function defined in the main program. I also want to have this module to be able to access variables defined in the main program after the program has started.
import socket
import time
import re
from plugins.say import *
host = "irc.somenetwork.net"
port = 6667
nick = "ircbot"
channels = "##bottesting"
s = socket.socket()
def connect():
s.connect((host, port))
s.send("NICK %s\r\n" % nick)
s.send("USER %s %s nul :%s\r\n" % (nick, nick, nick))
time.sleep(3)
s.send("JOIN %s\r\n" % channels)
time.sleep(3)
def sendMsg(chan, msgSend):
s.send("PRIVMSG %s :%s\r\n" % (chan,msgSend))
# print "Sending message \"%s\" to channel/user \"%s\"" % (msgSend, chan)
def quitServ(quitMsg="m8bot"):
s.send("QUIT %s\r\n" % quitMsg)
connect()
while 1:
msgRaw = s.recv(1024)
print msgRaw
if msgRaw == "":
break
if "PING" in msgRaw:
print "Pong!"
PONG = msgRaw.split(' ')
PONG[0] = PONG[0].replace('PING','PONG')
PONG = ' '.join(PONG)
s.send("%s\r\n" % PONG)
if "PRIVMSG" in msgRaw:
# print "PRIVMSG detected"
user = ''.join(re.compile("(?<=:).{0,}(?=.{0,}!)").findall(msgRaw.split(' ')[0]))
channel = msgRaw.split(' ')[2]
command = (' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[0]
msg = ''.join((' '.join(msgRaw.split(' ')[3:]).replace(":","",1)).split(' ')[1:]).replace("\r\n","")
if not "#" in channel:
channel = user
print "Nick: %s\nChannel: %s\nCommand: %s\nMsg: %s" % (user,channel,command,msg)
if ".quit" in command:
if msg:
quitServ(str(msg))
else:
quitServ()
if ".hello" in command:
# print "Attempting to send Hello World message."
sendMsg(channel, "Hello World!")
if ".say" in command:
say(msg)
quitServ()
This is my program. function say() is as follows:
def say(msg):
sendMsg(channel, "You said: %s" % msg)
I can see what the problem is, but I don't know how I would fix this. Feedback appreciated :)
-Nia

Try import __main__ in your say.py.
And then your say function should look something like this:
def say():
__main__.sendMsg(channel, "You said: %s" % msg)
But this is not a best solution. Just solution with less code changes.

Related

Black Hat Python proxy tool no data

I recently bought the book Black Hat Python, 2nd Edition, by Justin Seitz, which seems to be a very good book about networking and all that (i am writing my code on Kali Linux)
I have a problem on the TCP Proxy Tool on chapter 2 :
Here is the code :
import sys
import socket
import threading
HEX_FILTER = ''.join(
[(len(repr(chr(i))) == 3) and chr(i) or '.' for i in range(256)])
def hexdump(src, length = 16, show = True):
# basically translates hexadecimal characters to readable ones
if isinstance(src, bytes):
src = src.decode()
results = list()
for i in range(0, len(src), length):
word = str(src[i:i+length])
printable = word.translate(HEX_FILTER)
hexa = ' '.join(['{ord(c):02X}' for c in word])
hexwidth = length*3
results.append('{i:04x} {hexa:<{hexwidth}} {printable}')
if show :
for line in results :
print(line)
else :
return results
def receive_from(connection):
buffer = b""
connection.settimeout(10)
try :
while True :
data = connection.recvfrom(4096)
if not data :
break
buffer += data
except Exception as e:
pass
return buffer
def request_handler(buffer):
# perform packet modifications
return buffer
def response_handler(buffer):
# perform packet modifications
return buffer
def proxy_handler(client_socket, remote_host, remote_port, receive_first):
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((remote_host, remote_port))
if receive_first :
# Check for any data to receive before
going into the main loop (i guess)
remote_buffer = receive_from(remote_socket)
hexdump(remote_buffer)
remote_buffer = response_handler(remote_buffer)
if len(remote_buffer):
print("[<==] Sending %d bytes to localhost." % len(remote_buffer))
client_socket.send(remote_buffer)
while True : # Start the loop
local_buffer = receive_from(client_socket)
if len(local_buffer):
line = "[==>] Received %d bytes from localhost." % len(local_buffer)
print(line)
hexdump(local_buffer)
local_buffer = request_handler(local_buffer)
remote_socket.send(local_buffer)
print("[==>] Sent to remote.")
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print("[==>] Received %d bytes from remote." % len(remote_buffer))
hexdump(remote_buffer)
remote_buffer=response_handler(remote_buffer)
client_socket.send(remote_buffer)
print("[<==] Sent to localhost.")
if not len(local_buffer) or not len(remote_buffer):
# If no data is passed, close the sockets and breaks the loop
client_socket.close()
remote_socket.close()
print("[*] No more data. Closing connections. See you later !")
break
def server_loop(local_host, local_port, remote_host, remote_port, receive_first):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try :
server.bind((local_host, local_port)) # Bind the local host and the local port
except Exception as e:
print('Problem on bind : %r' %e)
# If an error occurs, prints a
print("[!] Failed to listen on %s:%d" % (local_host, local_port))
print("[!] Check for other listening sockets or correct permissions.")
sys.exit(0)
print("[*] Listening on %s:%d" % (local_host, local_port))
server.listen(5)
while True :
client_socket, addr = server.accept()
# print out the local connection information
line = "> Received incoming connection from %s:%d" % (addr[0], addr[1])
print(line)
# start a thread to talk to the remote host
proxy_thread = threading.Thread(
target = proxy_handler,
args=(client_socket,remote_host,
remote_port, receive_first))
proxy_thread.start()
def main():
if len(sys.argv[1:]) != 5:
print("Usage: ./proxy.py [localhost] [localport]")
print("[remotehost] [remoteport] [receive_first]")
print("Example : ./proxy.py 127.0.0.1 9000 192.168.56.1 9000 True")
sys.exit(0)
loca l_host = sys.argv[1]
local_port = int(sys.argv[2])
remote_host = sys.argv[3]
remote_port = int(sys.argv[4])
receive_first = sys.argv[5]
if "True" in receive_first:
receive_first = True
else :
receive_first = False
server_loop(local_host, local_port,
remote_host, remote_port, receive_first)
if __name__ == '__main__':
main()
(sorry, i had a bit of a trouble formatting it and it's quite long)
Now, normally, i just need to open 2 terminals and run the code with the command line :
sudo python proxy.py 127.0.0.1 21 ftp.dlptest.com 21 True
in one terminal, and :
ftp 127.0.0.1 21
in the other one.
My code seems to be working fine, except that... I receive no data. I tried different ftp servers (notice that i don't use the one quoted in the book), but it still doesn't work. It just says :
[*] Listening on 127.0.0.1
> Received incoming connection from 127.0.0.1:55856
but it doesn't actually displays anything until the connexion times out or that i stop the command with Ctrl + C.
I know this question has already been asked, but they don't resolve my problem.
Please tell me if i forgot a line of code (for example the one that prints the data on the screen lol) or did anything wrong :)
one the hexa variable you need to put and f'{ord(c):02x}' because you just have a string and not using the 'c' variable from the list comprehension. That's a small typo you missed fix that and try the whole process again.
hexa = ' '.join([f'{ord(c):02X}' for c in word])
The f should be here ^

How to get the output from the OSC receiving function with pyOSC

I have a very basic question, I suppose. I am using pyOSC library to receive OSC messages with Python.
The code I use is this:
import OSC
import time, threading
receive_address = '127.0.0.1', 9000
def printing_handler(addr, tags, stuff, source):
print "---"
print "received new osc msg from %s" % OSC.getUrlStr(source)
print "with addr : %s" % addr
print "typetags %s" % tags
print "data %s" % stuff
print "---"
s = OSC.OSCServer(receive_address)
s.addMsgHandler("/valueToNetwork", printing_handler)
st = threading.Thread( target = s.serve_forever )
st.start()
I then want to use the values in stuff as variables OUTSIDE the function, so I put return stuff; as last line but got a message when doing print printing_handler.
The message I get is: <function printing_handler at 0x76a78e70> in the sh window.

Python socket client doesn't exit

I'm trying to develop my simple server/client scripts to send some useful information about systems using platform module and saved in .txt file on the server side ( in order o improve my programming skills ) but when I run the client side it doesn't send any information till I closed using Ctrl+c but what I really want is the client to send informations then it close itself I tried the sys.exit but it doesn't work
this is the server Side
#!/usr/bin/python
import socket
import sys
host = ' '
port = 1060
s = socket.socket()
s.bind(('',port)) #bind server
s.listen(2)
conn, addr = s.accept()
print addr , "Now Connected"
response = conn.recv(1024)
print response
saved = open('saved_data.txt','w+')
saved.write(response) # store the received information in txt file
conn.close()
and this is the client side
#!/usr/bin/python
import socket
import platform
import sys
def socket_co():
port = 1060
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.107', port)) # my computer address and the port
system = platform.system()
node = platform.node()
version = platform.version()
machine = platform.machine()
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: ' + str(system) + '\n')
f.write('node: ' + str(node) + '\n')
f.write('version: ' + str(version) + '\n')
f.write('machine: ' + str(machine) + '\n')
sete = f.readlines() #read lines from the file
s.send(str(sete))
while True:
print "Sending..."
s.close()
sys.exit() #end the operation
def main():
socket_co()
if __name__ == '__main__':
main()
Data is cached in memory before sending. You have to flush after writing:
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: %s\n' % system)
f.write('node: %s\n' % node)
f.write('version: %s\n' % version)
f.write('machine: %s\n' % machine)
f.flush()
while True:
print "Sending..."
loops forever. So the problem is not in the send part.

IRC bot won't connect to server - Python

I don't know what I'm doing wrong. There are no errors or anything, It just keeps saying I'm not registered. This is also an IRC channel and network that does not require registering nicks to use. Thanks in advance.
#I've set variables and imported stuff up here
socket.connect((host, port))
socket.recv(512)
socket.send('NICK %s' % (username))
socket.send('USER %s %s %s :%s\r\n' % (username, username, username, username))
pingPong = socket.recv(512)
print pingPong
pingPong = pingPong[5:]
print 'PONG ' + pingPong
socket.send('PONG %s\r\n' % pingPong)
print 'PONG ' + host + '\r\n'
time.sleep(5) #I even added this time.sleep() to wait for the PONG to go through.
socket.send('JOIN %s\r\n' % channel)
socket.recv(1024)
#I have a while loop that continually receives data and commands down here
This outputs:
PING :912E235B
PONG :912E235B
:irc.va.us.mibbit.net 451 JOIN :You have not registered
Your NICK and USER commands are malformed. NICK should have an "\r\n" at the end. USER should not just be your username 4 times. Below is a working connection to that irc server.
import socket
host = "irc.va.us.mibbit.net"
port = 6667
username = "andrew"
channel = "luck"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print "recv 1", s.recv(512)
s.send('NICK %s\r\n' % (username,))
s.send('USER %s 8 * :%s\r\n' % (username, username))
pingPong = s.recv(512)
print "recv 2", pingPong
pingPong = pingPong[5:]
s.send('PONG %s\r\n' % pingPong)
s.send('JOIN %s\r\n' % (channel,))
msg = s.recv(1024)
print "Message", msg

one recv gets two or more send in python sockets

this is a simple socket program which has a server and some clients. clients send their texts encrypted by a simple RSA cryptography then the server side decrypts the sentence and then sends the decrypted sentence back to the client.
server:
import socket
import sys
from thread import *
from math import *
from random import *
import random
HOST = ''
PORT = 8888
size=2**16
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
def decoder(codedString,d,n):
breakcoded=[]
coded=(codedString)
#print coded;
for i in range (len(coded)):
breakcoded.append(chr(((int(coded[i])**d) % n)+48))
stri= ""
for i in range (len(breakcoded)):
stri+=breakcoded[i]
return stri
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
## data=s.recv(size)
l = int (data)
#print l
coded=[]
i=0
data1=conn.recv(size)
print 'Recieved n: ',data1
n = int (data1)
data2=conn.recv(size)
print 'Recieved d: ',data2
d = int (data2)
for i in range (l):
data3=conn.recv(size)
#print 'Recieved: ',data3
print
coded.append(data3)
print 'coded string has been recieved....'
print ('coded string: ' , coded)
d= decoder(coded,d,n)
print d
reply = 'OK... your message decrypted as: ' + d
if not d:
break
conn.sendall(reply)
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
client:
import socket
from math import *
from random import *
host='localhost'
port=8888
size=2**16
def declare():
a = sample([5,3],2)
return (a[0],a[1])
def coder(input_message):
(p,q)=declare()
for i in range (1):
p=2**p-1
for i in range (1):
q=2**q-1
#print p
#print q
#print ("n= ",p*q)
#print a
def gcd(a,b):
if a%b==0:
return b
elif a%b > 0:
s=a%b
return gcd(b,s)
else:
raise ValueError
n=p*q
phi=(p-1)*(q-1)
e=2
while gcd(phi,e)!=1:
e+=1
d=1
while ((e*d)%phi)!=1:
d+=1
public_key=(n,e)
special_key=(n,d)
ListOfAsciis=[]
coded=[]
breakcoded=[]
for i in input_message:
ListOfAsciis.append(ord(i)-48)
for j in ListOfAsciis:
coded.append((j**e)%n)
#print ("e= ",e)
#print ("d= ",d)
#print ("coded= ",coded)
for i in coded:
breakcoded.append(chr(((i**d) % n)+48))
#print ('n= ' , n)
#print str(coded)
#print coded
return (d,n,str(coded[0]))
def decoder(codedString,d,n):
#input_d= input("please enter your private key d: ")
#input_n= input("please enter your private key n: ")
#d = int (input_d)
#n = int (input_n)
breakcoded=[]
coded=(codedString)
print coded;
for i in range (len(coded)):
breakcoded.append(chr(((int(coded[i])**d) % n)+48))
stri= ""
for i in range (len(breakcoded)):
stri+=breakcoded[i]
return stri
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print 'socket created'
s.connect((host,port))
print 'connected'
data=s.recv(size)
print 'Recieved: ', data
while True:
input_message= raw_input("please enter your message: ")
message = list(input_message)
s.send(str(len(message)))
## (p,q)=declare()
#n=p*q
(d,n,c)=coder('i')
n=str(n)
print " ",
print " ",
print " ",
print " ",
s.send(n)
print " ",
d=str(d)
s.send((d))
print " ",
print " ",
print " ",
for i in range (len(message)):
(d,n,c)=coder(input_message[i])
print " ",
print " ",
print " ",
s.send((c))
print 'coded string has been sent to the server....'
data=s.recv(size)
print 'Recieved: ', data
now the problem is that the program sometimes works correctly and sometimes not! in false cases the server side gets two send items by the client by one recv. what should i
This is an inherent part of TCP. Stream sockets are byte streams, not message streams.
So, things are working exactly as they're supposed to. If you want to send a sequence of messages over a TCP stream, it's exactly the same problem as saving a sequence of objects to a file—you need some way of delimiting the messages. This could be as simple as using a stream of text, where newlines delimit the messages, or it could be a complex protocol, but it has to be something.
See this blog post for more detail.

Categories