Here is the complete code:
#client der mit irc-server kontakt aufnimmt
import time
import socket
from sys import argv
script, mitspieler1, mitspieler2 = argv
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
class funktion:
def main(self):
print "Socket(Client)"
host = "irc.iz-smart.net"
port = 6667
PASS = "7987fshd"
NICK = "Testikus"
USER = "Testikus localhost irc.iz-smart.net :Testikus"
self.login(PASS, NICK, USER, host, port)
print "Verbindung aufgebaut zu {0}(IP:{1})".format(
host, socket.gethostbyname(host)
)
self.haupt_schleife()
def haupt_schleife(self):
while True:
antwort = sock.recv(4096)
join = "JOIN #testblablub \r\n"
print antwort
if antwort[0:4] == "PING":
self.pong(antwort, join)
elif antwort.split()[3] == ":quiz.start":
sock.sendall("PRIVMSG #testblablub Es spielen mit: "
+mitspieler1+" und "+mitspieler2+"\r\n"
)
time.sleep(2)
self.fragen(antwort)
def pong(self, antwort, join):
sock.sendall("PONG " + antwort.split()[1] + "\n")
time.sleep(3)
sock.sendall(join)
sock.sendall("PRIVMSG #testblablub hi \r\n")
def login(self, PASS, NICK, USER, host, port):
sock.connect((host, port))
sock.sendall("PASS "+PASS+"\n")
sock.sendall("NICK "+NICK+"\n")
sock.sendall("USER "+USER+"\n")
def fragen(self, antwort):
sock.sendall("PRIVMSG #testblablub Welche Farbe hat der Himmel ? \r\n")
time.sleep(3)
if antwort.split()[3] == ":blau":
sock.sendall("PRIVMSG #testblablub RISCHTISCH \r\n")
ausfuehren = funktion()
ausfuehren.main()
(sry some strings are written in german, but I think that's not important)
So my main problem is that I want the function def fragen(self, antwort) to be run in the def haupt_schleife(self) function (or method for python's sake). All of the important stuff is in this def haupt_schleife(self). I want that the rest of the quiz-code to be running in the elif-block of the def haupt_schleife(self), so that it's a complete seperate thing. The stupid thing is, if I type in "quiz.start" the : sock.sendall("PRIVMSG #testblablub Welche Farbe hat der Himmel ? \r\n") is running with no problems, but it doesn't start the if-statement. It just does nothing else in the channel (just prints "Welche Farbe hat der Himmel ? out).
I hope that finaly someone understood this :/
(if you want to run the code you have to type in two names in the command line, because of argv)
IRC syntax
Sending messages should not be done this way:
PRIVMSG #testblablub Es spielen mit:
It should be:
PRIVMSG #testblablub :Es spielen mit ...
Also, USER should consist of 4 parts:
<username> <hostname> <servername> :<full name/realname>
In irc, it's important to end each string with \r\n
I noticed you sent \n sometimes and that will end badly, always end with \r\n!
Then comes sock.sendall(...), it's supposed to be used on say UDP sockets where you want to broadcast a message on all open sockets, in your case you're sending to and from a server, nothing else.. and it's via TCP so you should be using sock.send(...) (correct me if i'm wrong here)
A side note:
PING, it should only reply with PONG <server-name (usually sent with PING)>\r\n and not be spammed with JOIN every time, JOIN should be sent after MOTD is recieved, but sure it's not a problem really.. it will only annoy the sysadmins.
In your case it would probably be PONG irc.iz-smart.net\r\n and nothing else, no JOIN etc.
Now, to the problem
def haupt_schleife(self):
while True:
antwort = sock.recv(4096)
join = "JOIN #testblablub \r\n"
print antwort
if antwort[0:4] == "PING":
self.pong(antwort, join)
elif antwort.split()[3] == ":quiz.start":
sock.sendall("PRIVMSG #testblablub Es spielen mit: "
+mitspieler1+" und "+mitspieler2+"\r\n"
)
time.sleep(2)
self.fragen(antwort)
elif antwort.split()[3] == ":blau":
sock.sendall("PRIVMSG #testblablub RISCHTISH!\r\n")
Since self.fragen(...) only get called if the user writes quiz.start, the if check inside def fragen(...) will never be run again.. (because the next time the user write something, it's probably "blau" and that doesn't match ":quiz.start" which is the ONLY way in to the if check inside fragen(...).
def fragen(self, antwort):
sock.sendall("PRIVMSG #testblablub Welche Farbe hat der Himmel ? \r\n")
time.sleep(3)
So we removed the if block and made it an elif in haupt_schleife instead.
This is how the FIRST run/message would get parsed:
The next run, the message WOULD be green in fragen but it never reaches there because the only way to get there is via elif antwort.split()[3] == ":quiz.start": :)
You call the fragen function when this condition is true:
elif antwort.split()[3] == ":quiz.start":
Then, in the fragen function, you enter the if branch when this condition is true:
if antwort.split()[3] == ":blau":
Since the function got called, we know that antwort.split()[3] will be ":quiz.start", hence the if statement will never be executed.
You should recheck the logic behind your application.
Related
I have created a python script to detect an ARP attack. I have already initiated a ARP spoof attack and stored the wireshark capture in a pcap file. Once the code is executed, the code is designed to alert of any possible attack based on the MAC value change.
But how do I create a dictionary in the first place to store the MAC--IP mappings, and then detect when there is a change of values to indicate an alert?
Can anyone guide me please?
from scapy.all import *
mac_table = {}
def main():
pkts = rdpcap('/root/Desktop/arp_capture.pcap')
for packet in pkts:
if packet.haslayer(ARP):
if packet[ARP].op == 2:
try:
original_mac = req_mac(packet[ARP].psrc)
new_mac = packet[ARP].hwsrc
if original_mac != new_mac:
print(f"[**] ATTACK ALERT !!!!!! CHECK ARP TABLES !!![**]")
except IndexError:
pass
def req_mac(ip):
arp_req = ARP(pdst=ip)
bcst_req = Ether(dst='ff:ff:ff:ff:ff:ff')
p = bcst_req/arp_req
result = srp(p, timeout=3, verbose=False)[0]
return result[0][1].hwsrc
if __name__ == "__main__":
main()
I'm trying to create a remote using my phone for a game with sockets and pynput. Although some apps such as Chrome or Notepad detect and display the keys that have been pressed with the controller function of pynput (press and release), other ones (such as vba-m, the program I was interested in) just don't register any input. I've tried running the script with admin priviledges, but nothing has changed.
This is the code I'm using:
import socket,threading
from pynput.keyboard import Key, Controller
PORT=12345
SERVER="192.168.1.160"
ADDR=(SERVER, PORT)
FORMAT="utf-8"
TERMINATED="ADIOS"
server=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
conectados=[]
conectadosaddr=[]
keyboard = Controller()
def start(): #Función que se encarga de iniciar el servidor y escuchar nuevas conexiones
server.listen()
print("Servidor iniciado")
while True:
conn,addr=server.accept()
conectados.append(conn)
conectadosaddr.append(addr)
thread=threading.Thread(target=handle_client, args=(conn, addr))
thread.daemon=True
thread.start()
print(f"Conexiones activas: {len(conectados)}")
def handle_client(conn, addr): #Función que se encarga de manejar las conexiones
print(f"Nueva conexion de {addr}")
connected=True
while connected:
try:
data=conn.recv(1024).decode(FORMAT)
if data:
print(f"Recibido: {data} de {addr}")
if data==TERMINATED:
connected=False
print("Se ha cerrado la conexion pacíficamente de "+str(addr))
elif data in "WASDZX":
keyboard.press(data)
keyboard.release(data)
elif data=="BK":
keyboard.press(Key.backspace)
keyboard.release(Key.backspace)
elif data=="ST":
keyboard.press(Key.enter)
keyboard.release(Key.enter)
except Exception as e:
connected=False
print("ERROR: ",e)
print(f"{addr} se ha desconectado")
conectados.remove(conn)
conectadosaddr.remove(addr)
conn.close()
if __name__ == '__main__':
start()
I managed to fix the issue using a different library, called "pydirectinput". It does the same thing pynput does, but its presses are detected by vba-m and many other videogames
I have a zynq core board with its own processor , the zynq has hardcoded testfunctions which upon receiving the associated command for a function returns the data requested for example command 200 returns temperature sensor data . Using UDP in python I want to send commands to the zynq board.
Also the function will be called only upon defining the function parameters , MessageID is the command to be excuted , UniqueId and Overload is just a random number and Subgroup and SensorIndex are the inbuilt or fixed ids in the zyng for example group 0 and index 1 , this functions I have defined in another script called testfunctions def systemMonitorGetSensor(MessageID, UniqueID, Overload, Subgroup, SensorIndex):
import socket
import os
import testfunctions as test
def main(self):
def openconnection():
UDP_IP = "172.29.11.113" # Get local machine name
UDP_PORT = 4711 # Reserve a port for your service
MESSAGE = b"Hello SCE100...python talking"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
def ping():
UDP_IP = "172.29.11.113"
response = os.system('ping -c 1 ' + UDP_IP)
if response == 0:
print(UDP_IP, 'is up')
else:
print(UDP_IP, 'is down')
def stopsocket(self):
self.sock.shutdown(socket.SOCK_DGRAM)
self.sock.closes()
openconnection()
ping()
MessageID = int(input("Enter the TaskID to be executed : "))
print(MessageID)
main ( MessageID )
if MessageID == 200:
test.systemMonitorGetAllSensors(200,0,0)
if MessageID == 201:
systemMonitorResponce()
Writing a python script that sets up pickup games. srv.connect() will time out if the IP/RCON are put in wrong and/or the server is down altogether. I do not want the discord bot to crash just because a server is down so I am trying to use a try/except to keep the bot going. A person can start a pickup by typing !pickup size 4 servername ... and if srv.connect() can not get a handshake with the server, itll time out and send a message in discord saying it can not find the server. Then they could do !pickup size 4 servername2 and itll work. Problem right now is that after doing !pickup size 4 servername it seems stuck on saying the rcon/ip is down even though servername2 should be running just fine. Any help?
if(message.content.startswith('!pickup size')):
if(pickupActive == 0):
x = message.content.split()
if(len(x) >= 4):
pServer = x[3]
if(pServer in servers):
srv = Console(host=servers[pServer][0], port= servers[pServer][1], password=servers[pServer][2])
try:
srv.connect()
servercfg = srv.execute("servercfgfile")
#print(servers[pServer][3])
if (servers[pServer][3] in servercfg): #and (pickupActive == 0)): #change "server.cfg" to whatever your server configurtion filename is for pickup play. keep the quotations
totalPlayers = [" "] * int(x[2])
initialPlayerCount = len(totalPlayers)
pickupLeader = message.author.name
totalPlayers.insert(playerCount, pickupLeader)
totalPlayers.remove(" ")
PopulateTable()
await message.channel.send("```Pickup Game Starting! " + pickupLeader + " is the leader for the Pickup Game! Come join in! type '!pickup add' to join```")
await message.channel.send("```" + msg + "```")
pickupActive = 1
else:
await message.channel.send("`" + servers[pServer][4] + "`")
except:
await message.channel.send("Can not connect to the server for rcon..")
srv.disconnect()
else:
await message.channel.send("`Please specify the size of the pickup and a valid server name..`")
else:
await message.channel.send("`Proper formatting not used, please say !pickup size # server (Example: !pickup size 3 nwo)`")
else:
await message.channel.send("`Already a pickup game in progress, please add up to the current pickup game..`")
I need to built a python chat and I'm stacked in the very final step. I've built the server and the client and I have the following problem while running the code:
server.py 127.0.0.1
-in a separate window client.py 127.0.0.1
-another client
-type the nicknames to chat for both clients and get the correct answer 'yuppie' meaning you are connected
a client try to speak
message is not read by the other client until it doesn't print something, after printing it get the message printed on its screen correctly.
I'd like to get the message without being obliged to print something, it's pretty unrealistic!!! Code of client and server are below in 2 different classes. Thank you!
#! /usr/bin/env python
import socket,sys,select,re
PORT=1060
class Server():
def __init__(self,host):
#building listen_sock
self.listen_sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.listen_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.listen_sock.bind((host,PORT))
self.listen_sock.listen(20)
#building dict for socket and socket state
self.sockets={self.listen_sock.fileno(): self.listen_sock}
self.socket_state={self.listen_sock.fileno():''}
#building poll object
self.poll=select.poll()
self.poll.register(self.listen_sock,select.POLLIN)
#users' list
self.users_list={}
#DON'T LOOK HERE
#initialize the sender
#self.sender=0
# self.users=re.compile("\s*\$(get users connected)$\s*",re.IGNORECASE)
# self.nick=re.compile("\s*\$\$(\w*\d*)\$\$\s*",re.IGNORECASE)
# self.quit=re.compile("\s*\$(quit)\$\s*",re.IGNORECASE)
#self.commands=[self.users,self.nick,self.quit]
#funcion to receive message from client (work well)
def recv_until(self,fd,suffix):
self.message=''
#checking the end of the message
while not self.message.endswith(suffix):
data=self.sockets[fd].recv(16)
if not data:
raise EOFError('socket closed before we saw %r' % suffix)
self.message+=data
self.message=self.message[:-1]
#delete client (work well)
def del_client(self,fd):
del self.users_list[fd]
del self.socket_state[fd]
self.poll.unregister(fd)
#print the remaining active connections
if not len(self.users_list):
print 'Anyone is connected, waiting for new connection'
else:
print self.users_list
#add new client and change the of the file descriptor for that client (work well)
def new_client(self,fd):
newsock, sockname = self.listen_sock.accept()
print 'new connection from ', newsock.getpeername()
newsock.setblocking(False)
#recording the new connection
fd=newsock.fileno()
self.sockets[fd]=newsock
self.poll.register(fd,select.POLLOUT)
self.socket_state[fd]='ask nick'
#DON'T LOOK HERE
# def handle_query(self,fd):
# for n,command in enumerate(self.commands):
# match=command.search(self.message)
# if n==1 and match:
# self.users_list[self.sockets[fd].getpeername()]=match.group(1)
# print self.users_list
# for value in self.users_list.values():
# self.sockets[fd].sendall(value+'\n')
#starting the main function of the class
def chat(self):
while True:
#here il where the code hangs up waitng and waiting (WORKS BAD)
#return a tuple, identify where (fd) the event (event) is happening
for fd,event in self.poll.poll():
#print the state of each socket and the poll object
print self.socket_state
print self.poll.poll()
#starting the state machine
#remove closed sockets
if event & (select.POLLHUP | select.POLLERR |
select.POLLNVAL):
#deleting the socket closed at fd
self.del_client(fd)
#if the socket referred to is our listen_sock and we have a new connection request
elif self.sockets[fd] is self.listen_sock:
#recording the new entry!
self.new_client(fd)
#managing all the situation where it is necessary to answer to a client
#and changing the state of the socket and that of the sockets[fd]
elif event & select.POLLOUT:
if self.socket_state[fd]=='ask nick':
self.sockets[fd].sendall('identify\n')
self.poll.modify(self.sockets[fd],select.POLLIN)
self.socket_state[fd]='get user'
if self.socket_state[fd]=='invalid nick':
self.sockets[fd].sendall('invalid nick\n')
for value in self.users_list.values():
self.sockets[fd].sendall('\n'+value+'\n')
self.socket_state[fd]='ask nick'
if self.socket_state[fd]=='connected':
print '3'
self.sockets[fd].sendall('yuppie\n')
self.poll.modify(self.sockets[fd],select.POLLIN)
self.socket_state[fd]='ready to communicate'
if self.socket_state[fd]=='ready to receive':
self.sockets[fd].sendall(self.message)
print '4'
self.poll.modify(self.sockets[fd],select.POLLIN)
self.socket_state[fd]='ready to communicate'
#managing all the situation where it is necessary to get values from clients
elif event & select.POLLIN:
if self.socket_state[fd]=='get user':
self.recv_until(fd,'\n')
if self.message not in self.users_list.values():
self.users_list[fd]=self.message
self.poll.modify(self.sockets[fd],select.POLLOUT)
self.socket_state[fd]='connected'
else:
self.poll.modify(self.sockets[fd],select.POLLOUT)
self.socket_state[fd]='invalid nick'
if self.socket_state[fd]=='ready to communicate':
self.recv_until(fd,'\n')
print '5'
for i in self.users_list.keys():
if i!=fd:
self.poll.modify(self.sockets[i],select.POLLOUT)
self.socket_state[i]='ready to receive'
if __name__ == '__main__':
se=Server(sys.argv[1])
se.chat()
#! /usr/bin/env python
import sys,socket,select,threading,time
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST=sys.argv.pop()
PORT=1060
class Client():
def setup(self):
server_address=(HOST,PORT)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(server_address)
def chat(self):
while True:
time.sleep(1)
text=raw_input('>>> ')
self.sock.sendall(text+'\n')
def rec(self):
while True:
mess=self.sock.recv(16)
if mess:
print '$$$ ', mess,
def start(self):
l=threading.Thread(target=self.rec)
t=threading.Thread(target=self.chat)
t.start()
l.start()
if __name__=='__main__':
cl=Client()
cl.setup()
cl.start()
Next time take a look at http://www.zeromq.org/, it has a nice python binding http://zeromq.github.com/pyzmq/. It's perfect for this kind of stuff.