I am sending ssh count data from 'alphaclient' to 'alphaserver'. However the alphaclient server is not able to connect with alphaserver. Kindly help me resolve this error. I tried to kill the process at the port and restart the VMs but still getting the same issue.
This is the error output in alphaclient:
Traceback (most recent call last):
File "//./sshlogin-counter/alphaclient.py", line 82, in <module>
inform_alphaserver(client_message)
File "//./sshlogin-counter/alphaclient.py", line 45, in inform_alphaserver
c.connect((alphaserver_ip,port))
ConnectionRefusedError: [Errno 111] Connection refused
and this is the output in alphaserver:
Binding alphaserver at port 7888
Server Socket created.
Server socket binded at port 7888
Listening to port...
alphaclient.py
import os
import socket
input_file = os.path.join('/','var', 'log', 'auth.log')
#output_file = os.path.join('.','sshlogin-counter','client_message.txt')
total_ssh_attempts = 0
#Function1 that reads /var/log/auth.log and returns total ssh attempts made into that VM
def ssh_attempts(input_file):
successful_ssh_attempts = 0
invalid_ssh_attempts = 0
current_ssh_attempts = 0
with open(input_file,'r') as f:
f = f.readlines() #list of lines
for line in f:
if 'sshd' and 'Accepted publickey' in line:
successful_ssh_attempts+=1
#elif 'sshd' and 'Invalid user' in line:
#invalid_ssh_attempts+=1
current_ssh_attempts = successful_ssh_attempts + invalid_ssh_attempts
return (current_ssh_attempts)
#Function2 that informs Alphaserver of new ssh login attempts
def inform_alphaserver(client_message):
port = 7888
alphaserver_hostname = socket.gethostname()
alphaserver_ip = socket.gethostbyname(alphaserver_hostname)
print('Establishing connection with {} at port {} ...'.format(alphaserver_ip,port))
c = socket.socket()
print('Client socket created...')
c.connect((alphaserver_ip,port))
print('Client socket connected with {} at port {}'.format(alphaserver_ip, port))
client_message = client_message.encode()
print("Sending client message...")
c.send(client_message)
print("Message has been transmitted to alphaserver successfully")
c.close()
print("Connection Closed!!!")
#Monitor new ssh login attempts
while True:
#Function 1
current_ssh_attempts = ssh_attempts(input_file)
#Condition to test if new login attempts made
if current_ssh_attempts > total_ssh_attempts:
total_ssh_attempts = current_ssh_attempts
print('SSH login attempts detected!!!')
client_message = '{} had {} attempt'.format(socket.gethostname(), total_ssh_attempts)
#Function 2
#Send output file to Alphaserver
inform_alphaserver(client_message)
alphaserver.py
import os
import socket
#File for storing messages from Alphaclient
client_messages = os.path.join ('.','sshlogin-counter','client_messages.txt')
#Function that listens to client servers and receives client data
def receive_clientmessage():
port = 7888
host = socket.gethostname()
print('Binding {} at port {}'.format(host,port))
s = socket.socket()
print('Server Socket created.')
s.bind((host, port))
print('Server socket binded at port {}'.format(port))
s.listen(2)
print('Listening to port...')
while True:
c , addr = s.accept()
print("Connected with {}".format(addr))
client_message = c.recv(1024).decode()
client_hostname = list(str(client_message).split(" "))[0] #str converted to list and list[0] is the client_hostname
print("Client host name is {} ".format(client_hostname))
c.close()
break
#s.close()
return (client_hostname, client_message)
#Function to write client data to client_message.
def update_client_messages(client_hostname, client_message):
file = open(client_messages, 'r+')
f = file.read()
if client_hostname in f:
position = f.index(client_hostname)
file.seek(position)
file.write(str(client_message))
print('Updated client SSH login data')
file.close()
else:
file = open(client_messages,'a')
file.write('\n'+ str(client_message))
print('Added new client SSH login data')
file.close()
#Continuosly monitor and display client data
while True:
client_hostname, client_message = receive_clientmessage()
update_client_messages(client_hostname, client_message)
file = open(client_messages)
content = file.read()
print('----------------------------------------------------')
print(content)
print('----------------------------------------------------')
file.close()
Related
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
I am getting the above error..My server and client can send and receive their first messages but I get this error if I try to send more than one message.
My Server Code is here
import socket
import threading
import time
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5354
maxconnections = 9
ip = socket.gethostbyname(socket.gethostname())
print(ip)
server = (ip, port)
FORMAT = 'utf-8'
listensocket.bind((server))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
msg = f'\[ALERT\] {address} has joined the chat.'
lstbox.insert(0, msg)
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Client: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5986
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
And my client code is same with minor difference
import socket
import time
import threading
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5986
maxconnections = 9
ip = socket.gethostname()
print(ip)
FORMAT = 'utf-8'
host = 'MY_IP' # My actual ip is there in the code
listensocket.bind((host, port))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Server: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5354
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
Please let me know what changes are required to be made in order to make it run for every message.
I tried to put
g.connect((hostname, port))
the above line in the loop so that it will connect every time loop iterates. But it did not help.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
...
if at==0:
g.connect((hostname, port))
...
g.send(msg.encode())
at += 1
else:
...
g.send(msg.encode())
In the if at==0 condition it connects to the server, in the else part not. But is still trying to send something on the not connected socket.
I have a server using socket and multi threading in python I am trying to send data to one client, I can send to both clients using connection.sendall but that sends to both.
Is there a way to send to one client using something like IP address or socket id?
Here is my server.
import socket
from _thread import start_new_thread, get_ident
import pickle
import random
host = '127.0.0.1' #host for socket
port = 46846 #port
ThreadCount = 0
connections = 0
clients = []
name = []
turn = 1
word = random.choice(open('words.txt').read().splitlines()).lower().encode() #grab a word from my file of words
def game(connection): #the games code
print(get_ident()) #id of the socket
name.append(connection.recv(2048).decode('utf-8')) #wait for name
print(name)
while 1: # wait for 2 names
if len(name) == 2:
break
pickled_name = pickle.dumps(name) #encode names
connection.sendall(pickled_name) #send encoded names
connection.sendall(word) #send the word
connection.close() #end off the connection, I want more before this but this is the end for now
def accept_connections(ServerSocket): #start a connection
global connections
Client, address = ServerSocket.accept()
print(f'Connected to: {address[0]}:{str(address[1])}')
start_new_thread(game, (Client, ))
clients.append(Client)
connections = connections + 1
print(connections)
print(clients)
def start_server(host, port): #start the server
ServerSocket = socket.socket()
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print(f'Server is listing on the port {port}...')
ServerSocket.listen()
while True:
accept_connections(ServerSocket)
start_server(host, port)
And here is my client
import socket
import pickle
host = '127.0.0.1'
port = 46846
ClientSocket = socket.socket() #start socketing
print('Waiting for connection')
try:
ClientSocket.connect((host, port)) #connect
except socket.error as e:
print(str(e))
player = input('Your Name: ') #grab name
ClientSocket.send(str.encode(player)) #send name and encode it
data = ClientSocket.recv(1024)
name = ""
while name == "":
name = pickle.loads(data) #grab names from server
mistakeMade=0
print(f"Welcome to the game, {name[0]}, {name[1]}")
word = ClientSocket.recv(1024).decode('utf-8')
print("I am thinking of a word that is",len(word),"letters long.")
print("-------------")
turn = ClientSocket.recv(1024)
print(turn)
i am trying to make a server and client which sends a file from client to server and the server saves it to hard then the server asks for another file and if the answer of client is yes then the client sends the second file then the server again saves it and if the client answer is no server close the socket when i run this code the first file is sent
and received successfully but after that both of the server and the client freeze and nothing happens what is wrong with it and how can i fix it?
my server code:
import socket
host = 'localhost'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
(client, (ip, port))=s.accept()
while True:
data = "".join(iter(lambda: client.recv(1), "\n"))
with open('filehere.txt', 'w') as file:
for item in data:
file.write("%s" % item)
if not data: break
client.send("is there any other file?")
d = client.recv(2048)
if d == "yes":
while True:
data = "".join(iter(lambda: client.recv(1), "\n")
with open('filehere1.txt', 'w') as file:
for item in data:
file.write("%s" % item)
if not data: break
s.close()
else:
s.close()
my client code:
import socket
host = 'locahost'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
f = open('myfile.txt', 'rb')
l = f.read()
while True:
for line in l:
s.send(line)
break
f.close()
d = s.recv(2048)
a = raw_input(d)
if a == "yes":
s.send("yes")
f = open('myfile1', 'rb')
l = f.read()
while True:
for line in l:
s.send(line)
break
f.close()
else:
s.close
Why did you check a == "yes" on client side even when server is not sending "yes"
I think you can check a == "is there any other file?" insted
I was trying to make a simple chat room using Sockets in python3. When I ran my server on my localhost and set up clients using multiple terminals, everything went fine. When I tried to connect to the server (which was hosted on my system) by another system connected to same LAN network, this error came out.
ConnectionResetError: [Errno 104] Connection reset by peer
When I tried to reconnect from second system again and again it gave me another error
BrokenPipeError: [Errno 32] Broken pipe
This is my server.py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = "192.168.157.206"
PORT = 3000
addresses = {}
clients = {}
def Connections():
while True:
client, addr = server.accept()
print("{} is connected!!".format(addr))
client.send(("Welcome to Chat Room. Type {quit} to exit. Enter your name: ").encode("utf-8"))
addresses[client] = addr
Thread(target = ClientConnection, args=(client, )).start()
def ClientConnection(client):
name = client.recv(BufferSize).decode("utf-8")
client.send(("Hello {}".format(name)).encode("utf-8"))
message = ("{} has joined the chat..").format(name)
Broadcast(message.encode("utf-8"))
clients[client] = name
while True:
msg = client.recv(BufferSize).decode("utf-8")
if msg != "quit":
Broadcast(msg.encode("utf-8"), name + ": ")
else:
message = ("{} has left the chat.").format(clients[client])
Broadcast(message.encode("utf-8"))
client.send(("Will see you soon..").encode("utf-8"))
del clients[client]
break
def Broadcast(msg, name = ""):
for sockets in clients:
sockets.send(name.encode("utf-8") + msg)
server = socket(family=AF_INET, type=SOCK_STREAM)
try:
server.bind((HOST, PORT))
except OSError:
print("Server Busy")
BufferSize = 1024
server.listen(5)
print("Waiting for Connections... ")
AcceptThread = Thread(target=Connections)
AcceptThread.start()
AcceptThread.join()
server.close()
This is my client.py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = input("Enter Host IP: ")
PORT = eval(input("Enter Port No: "))
BufferSize = 1024
def Recieve():
while True:
try:
msg = client.recv(BufferSize).decode("utf-8")
print(msg)
except OSError:
break
def Send():
while True:
msg = input()
if msg == "quit":
client.send(msg.encode("utf-8"))
client.close()
break
else:
client.send(msg.encode("utf-8"))
client = socket(family=AF_INET, type=SOCK_STREAM)
client.connect((HOST, PORT))
RecieveThread = Thread(target=Recieve).start()
SendThread = Thread(target=Send).start()
Please tell me where I went wrong. I went through this answer here. But I cannot figure out where to correct this in my code.
Thanks in advance.
I have been able to receive the file from the socket and download it, but when I try to push a message from the server to the client the message is never displayed on the client side.
Below is the code and any help would be highly appreciated as I am a novice to network programming.
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
f = open("FileFromServer.txt", "wb")
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(Buffer)
while data:
f.write(data)
print("from connected user: " + str(data))
data = conn.recv(Buffer)
f.close()
print 'Data Recivede'
datas = 'Recived the file Thanks'
if datas is not '':
conn.send(datas) # send data to the client
conn.close() # close the connection
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
with open('T.txt', 'rb') as f:
print 'file openedfor sending'
l = f.read(1024)
while True:
client_socket.send(l)
l = f.read(1024)
f.close()
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print data
client_socket.close() # close the connection
print 'conection closed
The thing is that you both you server and client socket stuck in the while loop:
try this client.py:
import socket
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_socket = socket.socket() # instantiate
client_socket.connect((host, port)) # connect to the server
end = '$END MARKER$'
with open('T.txt', 'rb') as f:
print('file opened for sending')
while True:
l = f.read(1024)
if len(l + end) < 1024:
client_socket.send(l+end)
break
client_socket.send(l)
print('Done sending')
print('receiving data...')
data = client_socket.recv(1024)
print(data)
client_socket.close() # close the connection
print('conection closed')
server.py
import socket
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
Buffer = 1024
end = '$END MARKER$'
server_socket = socket.socket() # get instance
# look closely. The bind() function takes tuple as argument
server_socket.bind((host, port)) # bind host address and port together
# configure how many client the server can listen simultaneously
server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
# receive data stream. it won't accept data packet greater than 1024 bytes
with open("FileFromServer.txt", "ab") as f:
while True:
data = conn.recv(Buffer)
if end in data:
f.write(data[:data.find(end)])
conn.send(b'Recived the file Thanks')
break
f.write(data)
conn.close()