I'm trying to kick client from the server, and after that I get the follwing exception:
Exception in thread Thread-2 (__handle_client):
Traceback (most recent call last):
File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 36, in __handle_client
message = client.recv(1024).decode(FORMAT)
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "/Users/macbook/Desktop/Python Projects/Cars/Server/server.py", line 41, in __handle_client
client.send('You left the chat room'.encode(FORMAT))
OSError: [Errno 9] Bad file descriptor.
But when I use the exit function it is going well. Both using the __close_connection function.
This is my Code:
def __handle_client(self,client):
while True:
try:
message = client.recv(1024).decode(FORMAT)
if self.__handle_messsage(message,client) == True:
break
except:
client.send('You left the chat room'.encode(FORMAT))
self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',)
del self.__clientnick[client]
client.close()
break
def __handle_messsage(self,message,client):
if message == '/exit':
exit_message = 'You have discinnected successfully.'
self.__close_connction(exit_message,client)
return True
if message.startswith('/kick'):
if self.__clientnick.get(client) == 'admin':
for check_client in self.__clientnick:
if self.__clientnick.get(check_client) == message[6:len(message)]:
kick_message = 'You have been kicket from the chat room.'
self.__close_connction(kick_message,check_client)
return True
else:
client.send('You are not admin!'.encode(FORMAT))
def __close_connection(self,message,client):
client.send(message.encode(FORMAT))
self.__broadcast(f'{self.__clientnick[client]} has left the chat room!',client)
del self.__clientnick[client]
client.close()
It seems that you already closed the connection when you did kick and that is why you get the exception. the second exception is when you try to send a message to the closed connection.
Related
so, my error i get is: ((verify.darkys.wtf:3.8)) [darkehld#server196 verify.darkys.wtf]$ python main.py WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported Exception in thread Thread-2: Traceback (most recent call last): File "/opt/alt/python38/lib64/python3.8/asyncio/unix_events.py", line 95, in add_signal_handler signal.set_wakeup_fd(self._csock.fileno()) ValueError: set_wakeup_fd only works in main thread During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/alt/python38/lib64/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/opt/alt/python38/lib64/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/darkehld/virtualenv/verify.darkys.wtf/3.8/lib/python3.8/site-packages/discord/client.py", line 701, in run loop.add_signal_handler(signal.SIGINT, lambda: loop.stop()) File "/opt/alt/python38/lib64/python3.8/asyncio/unix_events.py", line 97, in add_signal_handler raise RuntimeError(str(exc)) RuntimeError: set_wakeup_fd only works in main thread
my main.py looks like this:
def discordbot(self):
self.bot = commands.Bot(command_prefix=".", help_command=None, intents=discord.Intents().all(),activity=discord.Game(name="Darkys Backup"))
#tasks.loop(seconds = 3)
async def myLoop():
for i in ListToSend:
membercount = str(len(Memberdb.GetMembers()))
channel = discord.utils.get(self.bot.get_all_channels(), id=int(self.log_channel))
embed = discord.Embed(title='', description="""
**✅ | Member verified**
≡ | User: <#{0}>
≡ | Ip: `{1}`
≡ | Member in db: `{2}`
""".format(i['userid'],i['ip'],membercount), color=5763719)
await channel.send(embed=embed)
guild = self.bot.get_guild(int(self.ServerId))
role = get(guild.roles, name=self.role_name)
try:
await get(self.bot.get_all_members(), id=int(i['userid'])).add_roles(role)
except:
pass
ListToSend.clear()
...
myLoop.start()
threading.Thread(target=self.bot.run,args=(self.BotToken,)).start()
now i think the error is because of the threading.thread line bumt idk for sure.
i tried changing self.bot.run to self.bot.start but then i get errors with never awaited.
Yep, you don't want to use a separate thread in conjunction with async.
Instead, just call self.bot.run(); it'll deal with everything for you, and yes, it will block until the bot ends.
i tried changing self.bot.run to self.bot.start but then i get errors with never awaited.
According to the docs start is a shorthand for login and connect, and will require to be awaited.
I have written a client and a server-side code to set a P2P type system with a server as a middleman to distribute a file to N clients.
I am getting this error OSError: [WinError 10022] An invalid argument was supplied in this chunk of my code on the server side
try:
for i in l:
print(i)
x = random.randint(0,N-1)
print(x,"Index")
serverSocketTCPRequest = serverSocketTCPList[x]
serverSocketTCPRequest.settimeout(2)
serverSocketTCPRequest.connect((i[0],i[1]))
serverSocketTCPRequest.send("SEND".encode())
serverSocketTCPRequest.send(str(chunkID).encode())
data = serverSocketTCPRequest.recv(1024)
serverSocketTCPRequest.close()
b = False
return data
except Exception as ex:
print(traceback.format_exc())
time.sleep(1)
# print(l)
pass
I am getting the following error:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
Traceback (most recent call last):
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 198, in sendChunkRequest
checkMessage, serverAddress = serverSocketUDPRequest.recvfrom(1024)
socket. Timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
My client side code for the same is
def handleTCP(client:Client):
global N
while(True):
try:
# print(clientList.index(client), client.clientSocketTCPRequest.getsockname())
client.clientSocketTCPRequest.listen(2*N)
client.clientSocketTCPRequest.settimeout(2)
connectionSocket, addr = client.clientSocketTCPRequest.accept()
print("Connected")
message = connectionSocket.recv(1024).decode()
if message.decode() == "SEND":
i = connectionSocket.recv(1024).decode()
connectionSocket.send(client.dict[int(i)])
connectionSocket.close()
elif message.decode() == "GET":
i = connectionSocket.recv(1024).decode()
client.dict[int(i)] = connectionSocket.recv(1024)
connectionSocket.close()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
m = template.format(type(ex).__name__, ex.args)
print(m,client.clientSocketTCPRequest.getsockname())
# print(traceback.format_exc())
continue
I can't think of a reason this is occurring. The client side shows just a timeout error on each of the N ports.
I have attached the entire client and server side codes and the file I'm trying to send.
I am new to network automation, and trying to use pyntc to ssh to the device. I am not sure how to write the code correctly to handle the ssh timeout or authentication error, etc.
My code is as below:
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
try:
DEVICE.open()
except Exception:
print('Error')
continue
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
I manually turned off this device, and then I found python code was quit:
root#Network-Automation:~/Pyntc# python3 pyntc_error_handling.py
Backing up ESW1
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 884, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.122.72
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyntc_error_handling.py", line 8, in <module>
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios_ssh')
File "/usr/local/lib/python3.5/dist-packages/pyntc/__init__.py", line 38, in ntc_device
return device_class(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 42, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 300, in open
verbose=False,
File "/usr/local/lib/python3.5/dist-packages/netmiko/ssh_dispatcher.py", line 246, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 317, in __init__
self._open()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 322, in _open
self.establish_connection()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 890, in establish_connection
raise NetMikoTimeoutException(msg)
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios 192.168.122.72:22
Looks like there are more than 1 errors ...
You are doing a minor mistake here, you are expecting an error than trying to same the output. In case of error, the script will through an error. Try it this way.
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
try:
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios')
DEVICE.open()
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
except Exception as Err:
print(Err)
I was trying to write a chat for a local network (the same with one represented in this tutorial). And when executing the code there have occured some mistakes. First of all,when one of the clients stops it's work with ctrl+c combination the command line of this client throws this exception
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "chat.py", line 39, in send_message
self.s.send(bytes(input(""),'utf-8'))
EOFError
and the client still works whithout exiting the program. The work of this client stops only when another client connects to the server. Then,another problem is that server crashes with that exception when one of the clients closes his widow with chat.
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Users\Samsung-PC\AppData\Local\Programs\Python\Python35-
32\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "chat.py", line 14, in handler
data=c.recv(1024)
ConnectionResetError: [WinError 10054]
And here is the code
import socket
import threading
import sys
class Server:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connections = []
def __init__(self):
self.s.bind(('192.168.56.1',9090))
self.s.listen(1)
def handler(self,c,a):
while True:
data=c.recv(1024)
for connection in self.connections:
connection.send(data)
if not data:
self.connections.remove(c)
c.close()
print(str(a[0])+':'+str(a[1]),'disconnected')
break
def run(self):
while True:
c,a =self.s.accept()
cThread=threading.Thread(target=self.handler,args=(c,a))
cThread.daemon=True
cThread.start()
self.connections.append(c)
print(str(a[0])+':'+str(a[1]),'connected')
class Client:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def send_message(self):
while True:
self.s.send(bytes(input(""),'utf-8'))
def __init__(self,addr):
self.s.connect((addr,9090))
iThread=threading.Thread(target=self.send_message)
iThread.daemon=True
iThread.start()
while True:
data=self.s.recv(1024)
if not data:
break
print(str(data,'utf-8'))
if (len(sys.argv) > 1):
client=Client(sys.argv[1])
else:
server=Server()
server.run()
How can I change this code to make it work on windows 10 without such mistakes (or any other mistakes))?
I want to return an error code when the following error gets raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 202, in create_group
ssh.connect(hostname, username=user, password=remotepass)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>
But I'm currently having trouble catching the error raised.
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
return 259
except socket.error:
return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest
Resulting on this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
except socket.error:
NameError: global name 'socket' is not defined
>>>
Any ideas?
Do
import socket
in the module where you do the exception handling.
To prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.