Replacing netcat using kali linux - python-2.7

This is the error I am receiving:
[*] Exception! Exiting.
Traceback (most recent call last):
File "bhnet.py", line 59, in <module>
client.close()
AttributeError: 'module' object has no attribute 'close'
Below is the code straight from the book I am following. Is there anyone that can tell me what is going on?
import sys, socket, getopt, threading, subprocess
#def some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
client = socket
def usage():
print "bhp net tool"
print
print "usage:bhpnet.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 write to [destination]"
print
print
print "examples:"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -c"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u =c:\\target.exe"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc.passwd\""
print "echo 'python' | ./bhpnet.py -t 192.168.8.135 -p 135"
sys.exit(0)
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#connect to our target host
client.connect((target,port))
if len(buffer):
client.send(buffer)
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
buffer = raw_input("")
buffer += "\n"
#send it off
client.send(buffer)
except:
print "[*] Exception! Exiting."
# tear down the connection
client.close()
enterkey()
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 our 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:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command.\r\n"
#send the output back to the client
return output
def client_handler(client_socket):
global upload
global command
global execute
#check for upload
if len(upload_destination):
#read in all of our bytes and write to our destination
file_buffer = ""
# keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
# now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
# acknowledge that we wrote the file out
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 recive until we see a linefeed
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_buffer)
#send back the response
client_socket.send(response)
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 options
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 buffer from the commandline
#this is will block, so send ctrl-D if not sending input
#to stdin
buffer = sys.stdin.read()
#send data off
client_sender(buffer)
#are we 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()
main()

#This code is tested and will work for you
import sys
import socket
import getopt
import threading`enter code here`
import subprocess
import pdb
# globals
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print
print "Usage: bhpnet.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 upon receiving connection upload a file and write to [destination]"
print
print
print "Examples: "
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -c"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e='cat /etc/passwd'"
print "echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.11.12 -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()
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"
if not listen and len(target) and port > 0:
buffer = sys.stdin.read()
client_sender(buffer)
if listen:
server_loop()
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((target, port))
if len(buffer):
client.send(buffer)
# wait for data back
while True:
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
buffer = raw_input("")
buffer += "\r\n"
print "[*] Sending: '%s'" % buffer
client.send(buffer)
except Exception as err:
print "[*] Exception! Exiting. %s" % err
client.close()
def server_loop():
global target
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()
client_thread = threading.Thread(target=client_handler,
args=(client_socket,))
client_thread.start()
def run_command(command):
command = command.rstrip()
print "[*] Processing command: %s" % command
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except Exception as err:
output = "Failed to execute command.\r\n"
return output
def client_handler(client_socket):
global upload
global execute
global command
if len(upload_destination):
file_buffer = ""
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
except:
client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
# check for command execution
if len(execute):
output = run_command(execute)
client_socket.send(output)
# another loop if command shell requested
if command:
while True:
client_socket.send("<BHP:#> ")
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
print "[*] Recv'd command: %s" % cmd_buffer
response = run_command(cmd_buffer)
client_socket.send(response)
main()

Related

Raspberry Pi (Python): Send SMS using SIM800L

Raspberry Pi 3
Python 2.7
Sim800L
Hi!
I am getting errors connecting to the gsm module
Here's the code I got from rhydolabz
import serial
import RPi.GPIO as GPIO
import os, time
GPIO.setmode(GPIO.BOARD)
# Enable Serial Communication
port = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=1)
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
port.write('AT'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('ATE0'+'\r\n') # Disable the Echo
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('AT+CMGF=1'+'\r\n') # Select Message format as Text mode
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('AT+CNMI=2,1,0,0,0'+'\r\n') # New SMS Message Indications
rcv = port.read(10)
print rcv
time.sleep(1)
# Sending a message to a particular Number
port.write('AT+CMGS="+6xxxxxxxxx68"'+'\r\n')
rcv = port.read(10)
print rcv
time.sleep(1)
port.write('Hello User'+'\r\n') # Message
rcv = port.read(10)
print rcv
port.write("\x1A") # Enable to send SMS
for i in range(10):
rcv = port.read(10)
print rcv
Here are the errors:
OSError: [Errno 11] Resource temporarily unavailable
raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 5] Input/output error
Sometimes It sends
Hello User
Login incorrect
raspberrypi login:
Sometimes
>
>
>
(100+ more '>')
Hello User
but almost always it doesn't connect and it gives Error 11
Have you experience this too?
Is there a way I can wait for the gsm to connect before I proceed on sending a message?
Did you disconnect the uart from the internal bluetooth and kernel console?
If you don't you will have a problem accessing the device. You need to disable the service that use it:
sudo systemctl disable hciuart
also disable kernel console on that uart eliminating
console=serial0,115200
from kernel command line (/boot/cmdline.txt).And you need to enable two overlays on the device tree (/boot/config.txt) Maybe this can help you:
dtoverlay=pi3-disable-bt
dtoverlay=pi3-miniuart-bt
Complet solution by rasberrypi.org: https://www.raspberrypi.org/documentation/configuration/uart.md

Is there a way to pipe binary stream to remote server using ssh and Python?

NOTE: not interested in any modules like Pramiko
I'm trying to save some binary data on remote server without creating local file.
As a test I read from file but later I'm replacing it with data feed:
ps = subprocess.Popen(['cat', "/delta/ftp/GSM.PRICINT_TBL.dmp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Next step I want to ssh data to remote server
ssh = subprocess.Popen(["ssh", '-XC', '-c', 'blowfish-cbc,arcfour', 'deltadmin#archiveserver', 'echo - >/tmp/test.log'],
shell=False,
stdin = ps.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
else:
print result
I use '-' so cat can accept standard input.
Expected result is data in /tmp/test.log but i see only
'-\n'
Any idea how to make it work?
I figured it:
echo 'test'|ssh -XC -c blowfish-cbc,arcfour bicadmin#nitarchive -T 'gzip - >/tmp/test.gz'
then on remote server:
zcat /tmp/test.gz
test
For cat we need space after redirect:
cat - > /tmp/test.txt

Sockets with Python

I have just started learning python. I just got to the chapter of sockets and came across the following code:
import socket
import sys
HOST = ''
PORT = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Our socket is created"
try:
s.bind((HOST, PORT))
except socket.error as e:
print "Error in binding the port"
sys.exit()
print "Binding is complete"
s.listen(20)
print "Server is in listen mode now!"
while 1:
conn, addr = s.accept()
print "Connected with the : " + addr [0] + ' : ' +str(addr[1])
s.close()
When i run the code it works fine, but when i try to connect to the port on 4444 i get the following error in the console which i can't figure out why:
I am trying to connect to localhost on port 4444 using putty, i tried ssh, telnet and raw and all of them yield the same error
Our socket is created
Binding is complete
Server is in listen mode now!
Connected with the : 127.0.0.1 : 49278
Traceback (most recent call last):
File "C:\pythontraining\Module12\server-working.py", line 24, in <module>
conn, addr = s.accept()
File "C:\Python27\lib\socket.py", line 206, in accept
sock, addr = self._sock.accept()
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
I think the error occurred from the socket that has not been available even the connection thread is alive.
Try fix indention on
s.close()
.
.
while 1:
conn, addr = s.accept()
print "Connected with the : " + addr [0] + ' : ' +str(addr[1])
s.close()

i am not able to send the complete text, as soon as i enter a character i get a reply and the connection closes.(i am new to python sockets)

import socket
import sys
host='' # Symbolic name meaning all available interfaces
port=7777 #random port
#creating socket
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "socket created"
#binding
try:
sock.bind((host,port))
except socket.error,msg:
print "Bind failed,Error no:"+str(msg[0])+"error:-"+str(msg[1])
sys.exit()
print "Bind successful"
sock.listen(10)
print "Listening" # it means that if 10 connections are already waiting to be processed, then the 11th connection request shall be rejected.
conn, addr=sock.accept()#accept new connection
print "connected to "+str(addr[0])+":"+str(addr[1])
#receive from client
data=conn.recv(1024)
print "received-"+data
conn.sendall(data*2)
#terminate
conn.close()
sock.close()
the above is the code for receiving data from a client and replying for it.
i used cmd with "telnet localhost 7777" to connect.
then i wanted to send a simple "hello world" message but i just typed "h" and i got a reply and the connection was terminated.
It has worked for me. Is your socketClient working correctly?
import socket
string='hello world'
print type(string)
HOST, PORT = 'localhost', 7777
# SOCK_STREAM == a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.setblocking(0) # optional non-blocking
sock.connect((HOST, PORT))
sock.send(string)
reply = sock.recv(1024) # limit reply to 16K
print(reply)
sock.close()
return reply

Python Socket: Compare Responses of Two Clients

I made a simple text based game and I want to create a multi-player mode to it.
I have a server and two clients:
CLIENT1 ----> SERVER <---- CLIENT2
Client1 sends number 7 to the server and Client2 sends number 5 to the server.
CLIENT1 -- 7 --> SERVER <-- 5 -- CLIENT2
Then the server add this numbers (7+5=12) and send this as a response to the clients.
CLIENT1 <-- 12 -- SERVER -- 12 --> CLIENT2
My question is how can I do this?
UPDATE
I've found a solution:
# -*-coding:utf8;-*-
import socket
import sys
from thread import *
HOST = ''
PORT = 3737
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
def clientthread(conn):
conn.send('Welcome to the server. Type something and hit enter\n')
while True:
data = conn.recv(1024)
return data
conn.close()
n = 0
l = []
while n < 2:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
d = clientthread(conn)
l.append(d)
print l[n]
n = n + 1
player1, player2 = int(l[0]), int(l[1])