pynput presses are not being detected by some programs - python

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

Related

Send a def with sockets in python

I have a problem with sockets, I wanna sent the especifications about my pc in a chat created with sockets, but when I use the sentence send() with the function the compiler throw this error... How can I send that information? Thanks. This is the server code.
#importar librerias
import psutil
import platform
from datetime import datetime
from socket import *
uname = platform.uname()
direccionServidor = "localhost"
puertoServidor = 9099
#Generar un nuevo socket
socketServidor = socket (AF_INET, SOCK_STREAM)
#Se establece conexion
socketServidor.bind((direccionServidor, puertoServidor))
socketServidor.listen()
def informacion():
print("="*40, "System Information", "="*40)
print(f"System: {uname.system}")
print(f"Node Name: {uname.node}")
print(f"Release: {uname.release}")
print(f"Version: {uname.version}")
print(f"Machine: {uname.machine}")
print(f"Processor: {uname.processor}")
while True:
# se establece conexion
socketConexion, addr = socketServidor.accept()
print("Conectado con cliente",addr)
while True:
#recibe el mensaje del cliente
mensajeRecibido = socketConexion.recv(4096).decode()
print(mensajeRecibido)
if mensajeRecibido == 'informacion':
socketConexion.send(informacion())
#condicion de salida
if mensajeRecibido == 'exit':
break
socketConexion.send(input().encode())
print("Desconectado del cliente",addr)
#cerramos conexion
socketConexion.close()
The error:
line 39, in <module>
socketConexion.send(informacion())
TypeError: a bytes-like object is required, not 'NoneType'
Like this:
def informacion():
msg = ["="*40, "System Information", "="*40]
msg.append(f"System: {uname.system}")
msg.append(f"Node Name: {uname.node}")
msg.append(f"Release: {uname.release}")
msg.append(f"Version: {uname.version}")
msg.append(f"Machine: {uname.machine}")
msg.append(f"Processor: {uname.processor}")
return '\n'.join(msg)
...
socketConexion.send(information().encode())

problem with send() function using socket in python

I'm using socket in python between 2 laptop to send informations. But I have an error and i can't resolve it. (I'm a debutant in python). The problem is when i trierd to send information with send() function
Traceback (most recent call last):
File "client.py", line 60, in <module>
client.send(GetMyInfo.scan())
TypeError: send() argument 1 must be string or buffer, not None
Maybe the error is due my function Getinfo ?
I'm using a class with functions (listinfo() here).
Thx
Here is the code :
import socket
import subprocess
import os,sys
#==========================================================================================
#creation d'une classe pour rendre le programme oriente objet
class GetInfo:
infos = os.uname()
currentUser = os.getlogin()
rep_actuel = os.getcwd()
myDirectory = os.listdir("/Users/")
def listInfo(self):
#afficher des informations sur le systeme
print "Informations du systeme :{} ".format(GetInfo.infos)
#afficher l'utilisateur actuel
print "Current user : {} \n".format(GetInfo.currentUser)
#afficher le path du repertoire actuel
print "Repertoire actuel : {} \n".format(GetInfo.rep_actuel)
def scan(self):
print "Liste de tous les repertoires dans Users/"
#on liste toutes les directories et sous directories
for file in GetInfo.myDirectory:
print file
#instance de l objet GetInfo (creation de l'objet)
GetMyInfo = GetInfo()
# afficage des infos de l'objet
#GetMyInfo.listInfo()
#GetMyInfo.scan()
#==========================================================================================
# on cree un objet socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "Socket successfully created"
# reservation d'un port specifique
port = 12345
# contient le nom d hote et le numero du port
#identifiant le serveur auquel on veut se connecter.
s.bind(('127.0.0.1', port))
print "socket binded to %s" %(port)
# activation du mode ecoute
# avec un nombre maximum de connexions qu il peut recevoir sur ce port sans les accepter
s.listen(5)
print "socket is listening"
#==========================================================================================
# gestion des erreurs
while True:
# on etabli la connection avec le client
client, addr = s.accept()
print 'Got connection from', addr
# send the informations about the victim.
client.send(GetMyInfo.scan())
print client.recvfrom(2048)
# on ferme la connection
s.close()

Using asyncio to read the output of a serial port

I have been doing some port-reading for work, and I need to know if I should use asyncIO to read the data that comes in from this port.
Here's some details about the way in which the system is constructed.
Multiple sensors are being read at the same time and might produce output that goes in at the same time. (all data comes in through a probee ZU10 connected to a usb port) All data must be timestamped as soon as it comes in.
The data is supposed to be processed and then sent to a django webapp through a REST API.
The thing Is, it's really important not to lose any data, I'm asking about this because I believe there must be an easier way to do this than the one I'm thinking of.
The way I want the data to come in is through an asyncronous process that takes in the data into a queue and timestamps it, this way there is no way in which loss of data is present, and timestamping may be no more than a few fractions of a second off, which is not a problem.
If anyone has got any ideas I would be thankful for them
Here's the code I'm using to open the port, take the data in and what I've got so far on the actually reading the meaningful data.
Here's the reading part:
import serial #for port opening
import sys #for exceptions
#
#configure the serial connections (the parameters differs on the device you are connecting to)
class Serializer:
def __init__(self, port, baudrate=9600, timeout=.1):
self.port = serial.Serial(port = port, baudrate=baudrate,
timeout=timeout, writeTimeout=timeout)
def open(self):
''' Abre Puerto Serial'''
self.port.open()
def close(self):
''' Cierra Puerto Serial'''
self.port.close()
def send(self, msg):
''' envía mensaje a dispositivo serial'''
self.port.write(msg)
def recv(self):
''' lee salidas del dispositivo serial '''
return self.port.readline()
PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
# test main class made for testing
def main():
test_port = Serializer(port = PORT)
while True:
print(test_port.recv())
if __name__ == "__main__":
main()
And a bit of what I'm going to be using to filter out the meaningful reads (bear with it, it might be full of awful errors and maybe a terrible RegEx):
import re
from Lector import ChecaPuertos
from Lector import entrada
patterns = [r'^{5}[0-9],2[0-9a-fA-F] $'] #pattern list
class IterPat:
def __init__(self, lect, pat = patterns):
self.pat = pat # lista de patrones posibles para sensores
self.lect = lect # lectura siendo analizada
self.patLen = len(pat) #Largo de patrones
def __iter__(self):
self.iteracion = 0 #crea la variable a iterar.
def __next__(self):
'''
Primero revisa si ya pasamos por todas las iteraciones posibles
luego revisa si la iteración es la que pensabamos, de ser así regresa una
tupla con el patrón correspondiente, y la lectura
de otra forma para el valor de ser mostrado
'''
pattern = re.compile(self.pat[self.iteracion])
comp = pattern.match(self.lect)
if comp == True:
re_value = (self.pattern, self.lect)
return re_value
else:
self.iteración += 1
def main():
puerto = ChecaPuertos.serial_ports()
serial = entrada.Serializer(port = puerto[0])
if serial != open:
serial.open()
while True:
iter = IterPat()
#This is incomplete right here.
I am using asyncio to read/write a serial port with pyserial. I am having my device on the other end of the serial connection write a single byte when it is ready to receive a payload. Asyncio watches for that byte then sends the payload. It looks something like this:
serial_f = serial.Serial(port=dev, baudrate=BAUDRATE, timeout=2)
def write_serial():
status = serial_f.read(1)
serial_f.write(buffer)
loop = asyncio.get_event_loop()
loop.add_reader(serial_f.fileno(), write_serial)

Enigma 2 and arduino

I'm newest with arduino i want to read informations from arduino and write it to dream Box DM800 enigma 2.
i tried this code and it didn't work
# Module de lecture/ecriture du port série
from serial import *
# Port série ttyACM0
# Vitesse de baud : 9600
# Timeout en lecture : 1 sec
# Timeout en écriture : 1 sec
with Serial(port="/dev/ttyACM0", baudrate=9600, timeout=1, writeTimeout=1) as port_serie:
if port_serie.isOpen():
while True:
ligne = port_serie.read_line()
print ligne
Can someone help me please

IRC BOT in Python, if in elif in while-loop

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.

Categories