I am having a problem with python code. In main thread i am creating a new threading holding a flask api with:
thread = Thread(target=app.run, kwargs={'host':'127.0.0.1', 'port':5000, 'debug':False, 'use_reloader':False})
then in main thread i have i while loop waiting for commands from terminal with:
while True:
command = input("> ")
the problem is that after some commands i get:
File "run.py", line 44, in cli_app
command = input("> ")
ValueError: I/O operation on closed file.
although my cli is still on and i can communicate from other terminals, that client can no longer create a command.
all i found was about opening csv files, thats why i am asking.
thanks in advace.
Are you trying to create terminal commands in flask, right? so flask have a decorators to make this easy :
import click
from flask import Flask
app = Flask(__name__)
#app.cli.command("create-user")
#click.argument("name")
def create_user(name):
#logic
return
And to Run this command you only need to write this command in terminal flask create-user admin, the first arg is the function and the second is the value(dont forget to use in this, you need to set FLASK_APP), for a complete doc look this flask doc
The other way, if you are using multiple server in same host, create a route like commands, and to call this command access the url.
#app.route("/user")
def create_user():
name= request.args.get('name')
#logic
return
And call it in url localhost:5001/user?name=Thomas
And create a script to run every server in background(i dont now if you are using gunicorn, so i use vallina thread pool`, and i using linux terminal)
nohup python server1/main.py &
nohup python server2/main.py &
nohup python server3/main.py &
nohup python server4/main.py &
nohup python server5/main.py &
Related
I am running a python multithreaded code which runs only once if i run it through python file but runs twice if i run it through Robot file :
python file code :
def connect():
print("Step 12: Reload devices")
config_threads_list = []
ipAddress = '172.22.12.14'
username = 'abcd'
password = 'abcd'
devices = ['5023','5024','5025','5026']
for ports in devices:
consoleServer, username, password, port = ipAddress, username, password, ports
print ('Creating thread for: ', ports)
config_threads_list.append(threading.Thread(target=obj.router_reload, args=(consoleServer, username, password, port)))
print ('\n---- Begin get config threading ----\n')
for config_thread in config_threads_list:
config_thread.start()
for config_thread in config_threads_list:
config_thread.join()
connect()
this code works fine when i run it through python only . However when i run it through robot framework its running twice
robot file :
Documentation Test case
Library <path to above py file >
*** Test Cases ***
TEST CASE LEL-TC-1
connect
Just to share why it is executed twice when you run the robot file.
You call connect() at the end of the Python file. This is the single invocation when the Python script is executed.
Now when you import the Python file as a library its actually gets executed. So the connect() will be called at the end. That is one.
Then you call it explicitly as a keyword in the test case. That is two.
To avoid this simply remove the connect() call from the end of the Python file.
Thanks to https://stackoverflow.com/users/4180176/joshua-nixon
after using the below mentioned simple/basic yet very effective code my issue has been resolved from robot file as well and code is only getting executed once :
if __name__ == "__main__":
connect()
I have a web server with CGI script calling python scripts.
When i try to execute in a main file (test1.py) another script called via
os.system('/var/www/cgi-bin/readIRtemp.py '+arg1+' '+arg2+' '+arg3)
I get his error message in /var/log/apache2/error.log :
import: not found
from: can't read /var/mail/jinja2
this is understandable for me since when called directly from the python console my script works !
its content is:
import sys, os
from jinja2 import Environment, FileSystemLoader, select_autoescape
last20values=sys.argv[1]
currTempInDegreesCelcius=sys.argv[2]
print('test '+last20values+' '+currTempInDegreesCelcius)
env = Environment(
loader=FileSystemLoader('/var/www/html/templates'),
autoescape=select_autoescape(['html', 'xml'])
)
template = env.get_template('IR.html')
updatedTemplate=template.render( arrayOfTemp = last20values, currTemp=currTempInDegreesCelcius)
Html_file=open("/var/www/html/IR.html","w")
Html_file.write(updatedTemplate)
Html_file.close()
I read somewhere something like maybe when calling os.system() the script is running with a different user account or some crazy things like that ... please help!
of course i chmod 777 * everything but that doesnt help ...
Objective:
I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux.
Problem:
I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper.
What I tried
Python Code:
import os
import wmi_client_wrapper as wmic
from socket import *
import time
wmic = wmic.WmiClientWrapper(
host ="192.168.115.128",
username = "LegalWrongDoer",
password = "sasuke14"
)
SW_SHOWNORMAL = 1
str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'"
os.system(str)
print("Folder sent")
process_startup = wmic.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup)
process_startup.ShowWindow = SW_SHOWNORMAL
if result == 0:
print("Process started successfully")
else:
print("Sorry, but can't execute Process!")
When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails.
Further Traceback Calls:
Traceback (most recent call last):
File "WMIClient.py", line 22, in <module>
process_startup = wmic.Win32_ProcessStartup.new()
AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup'
I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
Well I finally managed to get a work-around for this whole scenario, and it might look a little messy but it sure does work for me.
Firstly I use smbclient to transfer the executable to the end-point where I want to execute it. Inside my code I use os.system() calls to make this happen.
import os
str1 = "smbclient //'<HostMachineIP>'/admin$ -U '<domain>\\<username>%<password>' -c \'lcd /usr/local/acpl/bin/endPoint/; put \"EndPointForeignsics.exe\"\'"
os.system(str1)
This helps me put the executable in desired shared folder that the user has access(Admin in my case) to and then use WMI-query through a tool called Winexe to get access to the console/command prompt of the end-point. I use another os.system() call to execute this again.
str2 = r'/usr/local/bin/winexe -U "<domain>\\<username>%<password>" //<HostMachineIP> "cmd /c c:\windows\EndPointForeignsics.exe '
os.system(str2)
P.S:-- Winexe is a tool that you'll have to download off the internet and compile it. It may take some time and effort to do that, but is quite achievable. You'll get a lot of help on the same from StackOverflow and Documentation of the tool.
What I want to achieve:
I would like to create a python script to deactivate Django users in the database from the CLI. I came up with this:
$ sudo python manage.py shell
>>> user = User.objects.get(username=FooBar)
>>> user.is_active = False
>>> user.save()
>>> exit()
The above code WORKS when I manually enter it manualy command after command. However, I would like to put execute the commands in one .py script like
$ sudo python script.py
Now I've tried diffirent aproaches:
os.system("command1 && command2 && command3")
subprocess.Popen("command1 && command2 && command3",
stdout=subprocess.PIPE, shell=True)
The problem:
This does not work! I think this problem is here because Python waits until the opened Django shell (first command) finishes which is never. It doesn't execute the rest of the commands in the script as the first command puts it in Hold.
subprocess.popen can execute commands in a shell but only in the Python shell, I would like to use the Django shell.
Anyone ideas how to access the Django shell with a .py script for custom code execution?
Firstly, you should not be accessing your Python shell with sudo. There's no need to be running as root.
Secondly, the way to create a script that runs from the command prompt is to write a custom manage.py script, so you can run ./manage.py deactivate_users. Full instructions for doing that are in the documentation.
Try to input the commands to the running django-shell as a here document:
$ sudo python manage.py shell << EOF
user = User.objects.get(username=FooBar)
user.is_active = False
user.save()
exit()
EOF
If you want to execute a Python script that accesses Django models, you first need to set an environment variable:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<path>.settings")
In which you need to replace <path> by your project directory, the one that contains the file settings.py.
You can then import your model files, for example:
from <path>.models import User
user = User.objects.get(username=FooBar)
user.is_active = False
user.save()
Based on the comment by Daniel earlier in this thread I've created a simple script to get the job done. I'm sharing this for readers of this thread who are trying to achieve the same goal. This script will creates a working "manage.py deactivate_user" function.
This is an example reference of your Django app folder structure:
You want to create the "deactivate_user.py" file and place it in management/commands/deactivate_user.py directory.
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
class Command(BaseCommand):
help = 'Deactivate user in the database'
def handle(self, *args, **options):
username = raw_input('Please type the username of the user you want remove: ')
try:
user = User.objects.get(username=username)
user.is_active = False
user.save()
print ('User is now deactivated in the database.')
except User.DoesNotExist:
print ('Username not found')
Call the script by using "python manage.py deactivate_user" You can also create an "activate_user" script with the same code but instead of user.is_active = False use = True.
If you're using Django 1.8+, then another useful option is to write your own script, and call it with manage.py runscript.
For example, you can write a script named db_init.py and put it under utils folder.
Then launch this script with:
python3 manage.py runscript utils.db_init
Reference:
https://django-extensions.readthedocs.io/en/latest/runscript.html
Open Django Shell python manage.py shell
Then run execfile('filename.py')
As Daniel Roseman mentions, OP will want to
create a script that runs from the command prompt is to write a custom manage.py script, so you can run ./manage.py deactivate_users
Since the command OP wants to run deals with users, OP wants to place it in the user app. Create in the user app a management/commands directory. That's the place where OP is going to have all of the custom commands of that app. A good name for the file with the command is delete_user_from_database.py. It should look like this
app/
init.py
models.py
management/
init.py
commands/
init.py
delete_user_from_database.py
tests.py
views.py
Then, paste the following code inside of the previously created file (management/commands/delete_user_from_database.py)
from django.core.management.base import BaseCommand
from user. models import User
class Command(BaseCommand):
help = 'Delete user from database'
def add_arguments(self, parser):
parser.add_argument('username', type=str, help='username of the user to delete')
def handle(self, *args, **kwargs):
username = kwargs['username']
usr = User.objects.get(username=username)
usr.delete()
If one doesn't want to really delete the user but, instead, make the user inactive, then in the previous code change
usr.delete()
to
usr.is_active = False
usr.save()
Save the file and one can see one's newly created command in the list of the existing commands by running
python manage.py help
Now assuming we want to delete a user with the username goncaloperes, then we can simply run
python manage.py delete_user_from_database goncaloperes
Read more about Django custom management commands
How can I fetch the title of a screen session from the command line?
I came up with a very small and simple python script with pexpect to do it.
It is handy in multiuser environments where some host is reserved and status is written to screen title by user.
It works for me, feel free to make it better.
In order to fetch specific session title, you need to modify the script and call for correct session.
If you run this through remote connection as local script (through SSH for example), remember to set export TERM=xterm before execution.
try:
import pexpect
import sys
child=pexpect.spawn('screen -x')
child.sendcontrol('a');
child.send('A');
i = child.expect('Set window.*')
child.sendcontrol('c');
child.sendcontrol('a');
child.send('d');
TITLE=str(child.after)
TITLE_P=TITLE.split('7m')
if str(TITLE_P[-1]) == '':
print 'Title not found'
else:
print str(TITLE_P[-1])
except:
print 'Could not check screen Title'