0

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'"?

KnightOfNi
  • 770
  • 2
  • 10
  • 17
  • It does sound very odd. Why not print the command on the client before it executes just to get a better understanding? – dilbert May 27 '14 at 22:20
  • I think `bytes(command, 'UTF-8')` might have something to do with it. – dilbert May 27 '14 at 22:22
  • @dilbert Well, I do need to encode it before I send it off... I'll try the printing before executing thing and see what happens. – KnightOfNi May 27 '14 at 22:28

1 Answers1

0

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?

Community
  • 1
  • 1
Nick
  • 115
  • 2
  • 5
  • Right! I originally forgot to encode it at all, so I never thought to put in the decoding afterwards. Thanks! – KnightOfNi May 27 '14 at 22:31