For educational purposes, I set up a server that allows remote command execution on Windows - or rather, I tried to. For some reason, the command line refuses to recognize some of the commands I send, but others work fine. For instance, sending the command echo "Hello World!!!" causes, as it should, a cmd window to pop up reading "Hello World!!!". Fine. But when I send the command shutdown /s /t 30 it gives me the improper syntax / help screen for the shutdown command. When I send the command msg * "Hello World" it tells me that 'msg' is not a recognized internal or external command, operable program, or batch file. Here is my server code:
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 4242)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()
print("Connection established with %s " % str(client_address))
while True:
command = input("Enter a command: ")
connection.send(bytes(command, 'UTF-8'))
confirm = connection.recv(128)
if confirm == "yes":
print("[+] Command executed successfully.")
else:
print("[-] Command failed to execute!!!")
And here is my client code:
import socket
import sys
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('', 42042)
sock.bind(server_address)
sock.connect(('192.168.1.5', 4242))
while True:
command = str(sock.recv(1024))
try:
os.system(command[2:]) # an odd thing, the commands somehow came out prefaced with "b'". Ideas?
sock.send(bytes("yes", 'UTF-8'))
except:
sock.send(bytes("no", 'UTF-8'))
So yeah, that's that. The fact that only SOME commands are getting screwed up is really confusing me. Anybody have any ideas? Also, what's up with that "b'"?
str(sock.recv(1024)) is not the way to convert a bytes object into a string, you should be using the sock.recv(1024).decode('UTF-8') method
You can look at the documentation for bytes.decode https://docs.python.org/3.4/library/stdtypes.html#bytes.decode
Or this related question Best way to convert string to bytes in Python 3?
Related
I was writing a TCP shell script to run some CMD commands on a server (laptop). I got some basic commands working like ipconfig and whoami and got the output sent back to the client terminal.
when I tried to run this command: curl https://media.wired.co.uk/photos/607d91994d40fbb952b6ad64/4:3/w_2664,h_1998,c_limit/wired-meme-nft-brian.jpg --output yo.jpg it would show this on the server terminal:
output of server terminal after running command
I tried running this command manually on the server and it worked fine, anyone knows why is this happening?
Client Code:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.settimeout(1.0) # waiting 1 second for data to be sent back before continuing from s.recv
while True:
command = input("Enter command:\n")
s.sendall(command.encode())
try:
data = s.recv(2048) # Waiting for data to be sent back
except socket.error: # Checking if there is data
print("NO DATA")
else:
print(data.decode()) # Decode the data
Server Code:
import socket
import os
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
PORT = 5000
sock.bind(('', PORT))
sock.listen(5)
try:
while True:
newSocket, address = sock.accept()
print("Connected from", address)
while True:
receivedData = newSocket.recv(2048)
receivedData = receivedData.decode()
print(str(receivedData))
output = os.popen(receivedData).read()
output = str(output)
newSocket.sendall(output.encode())
newSocket.close()
print("Disconnected from", address)
finally:
sock.close()
CD command was overwritten by the curl command after it, in order to curl to a specified directory both cd and curl command need to be inputted at the same time with the '&' operator.
cd C:\Users\User\Desktop && curl https://media.wired.co.uk/photos/607d91994d40fbb952b6ad64/4:3/w_2664,h_1998,c_limit/wired-meme-nft-brian.jpg --output yo.jpg
I am trying to implement sockets with python.the following code works well without the while loop..but with the while loop, for the second iteration , it gets stuck in s.sendall().could you please suggest how to fix this ?
def main():
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print "Connected to Server!"
while True:
print "Enter your Command:"
command = raw_input()
if(command):
try:
sock.sendall(repr(command))
except socket.error:
print "Socket Error Occured"
data = sock.recv(1024)
if data:
print('Received', repr(data))
else:
print "No Data"
else:
os.system("clear")
sock.close()
if __name__ == "__main__":
main()
Hello
I don't have all the information I need to make this post as
informed as I'd like, however I can make some educate
d guesses and try my best to explain what I think is going wrong. Are you ready?? Lets get into it.
So,
You start off by making a tcp socket and then connecting to a server hosted locally on port 11111
host = socket.gethostname()
port = 11111
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
next you enter a loop
while True:
#input command, request eval
Here your goal is to take user input and send it to a server to eval. You do that with
#get user input
print "Enter your Command:"
command = raw_input()
#send command to server for eval
sock.sendall(repr(command))
#receive then print eval
data = sock.recv(1024)
print('Received', repr(data))
this works and sends commands as you'd expect, although sending repr(command) might not be what you want to send
command = "1+1"
eval(command)
//2
eval(repr(command))
//'1+1'
Now
Here is where I have to make some assumptions
Early on you connected to a server
sock.connect((host, port))
I'm assuming that the server accepts your connection evals your command and sends the answer back. Something like
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind('localhost',11111)
sock.listen()
while True:
conn, addr = sock.accept()
command = conn.recv(1024)
sock.sendall(eval(command))
If this is the case then your connection might fail because your eval server runs eval once and then accepts a new connection.
That means that your client can no longer send to, or recieve data from, the server
I hope this helps.
I just created an python script that solve me a problem i need but i want to convert this script to exe file to run it in any windows machine without need of install python on it
I have search of how could i convert the py to exe and run it and i have found that i could use script called py2exe the problem here that i want to convert my file to exe and run it as a windows service continuously on the my PC.
Here is the my script:
import socket, sys, serial
HOST = '' # Symbolic name, meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
# try:
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
# print('Connected with {}:{}'.format(addr[0], addr[1]))
str = conn.recv(100)
n_str = str[8:]
last_c = n_str.find('%')
last_str = n_str[:last_c]
final_str = last_str.replace('+',' ')[:-3]
print(final_str)
try:
pole = serial.Serial('COM4')
pole.write(' \r\n')
pole.write(final_str+'\r\n')
pole.close()
except:
print(Exception.message)
s.close()
Could i have some help here
Python is an interpreted language, not a compiled one. As such, it needs its interpreter in order to be executed.
Bearing that in mind, you can use this: http://www.py2exe.org
More options given here: a good python to exe compiler?
or even better, in here: https://wiki.python.org/moin/DistributionUtilities
Im wondering is there any way to find out the socket that is open and then to close it?
For instance,I have a script "SendInfo.py" which opens a socket and sends some info over TCP.
If I call this script to run it e.g. "python SendInfo.py" , it will open a new socket.
If I run this script again using "python SendInfo.py", which will send some more up to date information, I would like to cancel the previous TCP transaction and start a new one - e.g. by closing the previous socket.
How do I get access to the open socket at the beginning of my script in order to close it? Ive tried looking into threads, but Im similarly confused about which threads are open and how to close open threads etc.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(2)
s.connect((self.__host, PORT))
I'm not sure if this is what you are after but here is a method of ensuring that the script is only running once and killing an existing running script.
You may find something useful in it. (This is for Linux)
#!/usr/bin/python
# running.py
# execute by making the script executable
# put it somewhere on $PATH and execute via running.py
# or execute via ./running.py
import os, sys, time , signal, socket
running_pid = os.popen('ps --no-headers -C running.py').read(5)
try:
running_pid = int(running_pid)
except:
running_pid = 0
current_pid = int(os.getpid())
if running_pid != 0:
if running_pid != current_pid:
print "Already running as process", running_pid
print "Killing process", running_pid
os.kill(int(running_pid), signal.SIGKILL)
# sys.exit()
# Create a listening socket for external requests
tcp_port = 5005
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print "Error on Socket 5005"
# force re-use of the socket if it is in time-out mode after being closed
# other wise we can get bind errors after closing and attempting to start again
# within a minute or so
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.settimeout(0.10)
sock.bind(("localhost", tcp_port))
except IOError as msg:
print "Error on Socket Bind "+str(tcp_port)+", running.py is probably already running"
pass
try:
sock.listen((1))
except:
print "Error on Socket listen"
time.sleep(60)
sock.close()
I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code:
import sys, os, socket
host = ''
port = 50103
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: ", port)
s.listen(1)
while (1):
conn, addr = s.accept()
print 'New connection from ', addr
try:
while True:
rc = conn.recv(2)
pipe = os.popen(rc)
rl = pipe.readlines()
fl = conn.makefile('w', 0)
fl.writelines(rl[:-1])
fl.close()
except IOError:
conn.close()
And here is my client:
import sys, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = input('Port: ')
s.connect((host, port))
while (1):
cmd = raw_input('$ ')
s.send(cmd)
file = s.makefile('r', 0)
sys.stdout.writelines(file.readlines())
file.close()
Here is my problem. I start the server and then run the client on the same machine. I enter the port and connect. Then I get the raw_input which is the '$'. If I type a command like 'ls' it just hangs on the client side. I have to exit the server for the client to receive the output of ls. By the way I am running Ubuntu Linux. Not sure if that matters.
When you makefile() on the socket and then use readlines() on it, it will continue until you reach an end of file, which in the socket case is that it closed from the other end.
Using makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and recv() on both ends.
You probably also want to have some sort of actual "protocol" so the server tells the client "HERE COMES A RESPONSE" and "THIS IS THE END OF THE RESPONSE" so that the client knows. Otherwise it gets hard to know when to stop waiting for more response. :)
Update with an example that works:
server.py:
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 50500))
print("Server started")
s.listen(1)
while True:
print "Accepting"
conn, addr = s.accept()
print 'New connection from ', addr
while True:
try:
rc = conn.recv(1024)
print "Command", rc
if not rc.strip():
continue
if rc.strip() == 'END':
print "Close"
conn.send("**END**")
conn.close()
break
else:
conn.send("This is the result of command %s\n" % rc)
except Exception:
conn.close()
sys.exit()
client.py
import sys, os, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 50500))
while True:
cmd = raw_input('$ ')
s.send(cmd)
result = s.recv(1024)
print result
if result == "**END**":
print "Ending"
break
Well for one thing you're only connecting on the client once and on the server you're closing the socket after every read.
You should take a look at this example.
http://ilab.cs.byu.edu/python/socket/echoserver.html
You're doing quite a few things incorrectly.