Call custom AutoIt function from python - python

I found a way to run built in auto it functions from python using the following code
from win32com.client import Dispatch
Auto = Dispatch("AutoItX3.Control")
Auto.Run("notepad.exe", "", 5)
Is there a similar way to call custom methods i.e methods defined in my_AutoIt_File.au3
Say I have a method in this file
Func my_autoit_method
;some code
EndFunc
Is there a way to call this my_autoit_method from python?

From the help file:
AutoIt specific command Line Switches
Form1: AutoIt3.exe [/ErrorStdOut] [/AutoIt3ExecuteScript] file
[params ...]
Execute an AutoIt3 Script File
/ErrorStdOut Allows to redirect fatal error to StdOut which can be captured by an application as Scite editor. This switch can be used with a compiled script.
To execute a standard AutoIt Script File 'myscript.au3', use the command:
'AutoIt3.exe myscript.au3'
Form2: Compiled.exe [/ErrorStdOut] [params ...]
Execute an compiled AutoIt3 Script File produced with Aut2Exe.
Form3: Compiled.exe [/ErrorStdOut] [/AutoIt3ExecuteScript file]
[params ...]
Execute another script file from a compiled AutoIt3 Script File. Then you don't need to fileinstall another copy of AutoIT3.exe in your compiled file.
Form4: AutoIt3.exe [/ErrorStdOut] /AutoIt3ExecuteLine "command line"
Execute one line of code.
To execute a single line of code, use the command:
Run(#AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(0, ''Hello World!'', ''Hi!'')"')

You have to expose your AutoIt Function to other applications. This could be done easily with AutoItObject, which can register an object in the ROT.
The AutoIt Code would be:
#include <AutoItObject.au3>
$oObject = _AutoItObject_Create()
_AutoItObject_RegisterObject($oObject, 'MyVery.CustomApplication')
_AutoItObject_AddMethod($oObject, '_my_custom_function', '_my_custom_function')
While Sleep(100)
WEnd
Func _my_custom_function($oSelf)
MsgBox(0, '', 'AutoIt says Hi')
Exit
EndFunc
The Python Code should be:
from win32com.client import Dispatch
Auto = Dispatch("MyVery.CustomApplication")
Auto._my_custom_function()

Related

Python script called from PHP can't write a file

I have a problem with converting docx to pdf files in my script.
At first I tried to use a pure php-based solution, described here:
https://stackoverflow.com/a/20035739/12812601
Unfortunatelly this does not work (it creates an empty com object, then throws a fatal error).
So I've tried to use a python script to do this.
I use a great script from here:
https://stackoverflow.com/a/20035739/12812601
So here is a problem.
The Python script standalone (run via a command line) works just fine, and saves the converted pdf. Unfortunatelly when I try to call it via PHP it can't save a converted file.
PHP scripts can create and write files oin the same directory without any problem
This supposed to be a local configuration, so I do not care about any portability
Scripts:
*******PHP*******
<?php
//Script only for testing Python calls, tried different methods
error_reporting(E_ALL);
echo '<h1>Begin</h1>';
echo '<h2>Before call</h2>';
exec ('python dp.py');
echo '<h2>After exec call</h2>';
system('python dp.py');
echo '<h2>After Sys Call</h2>';
passthru('python dp.py');
echo '<h2>After Pass Call</h2>';
$w = get_current_user();
var_dump($w);
?>
*****Python*****
import sys
import os
import comtypes.client
import win32com.client
wdFormatPDF = 17
#static file names for testing
in_file = 'C:\\Users\\fake_user\\OneDrive\\Stuff\\f1.docx'
out_file = 'C:\\Users\\fake_user\\OneDrive\\Stuff\\f3.pdf'
print('BEGIN<br>\n')
word = win32com.client.Dispatch('Word.Application')
word.Visible = False
doc = word.Documents.Open(in_file)
print('\nOpened Docx\n<br>')
print(in_file);
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
print('\nSaved\n<br>')
doc.Close()
word.Quit()
print('DONE\n')
*****Output from the browser*****
Begin
Before call
After exec call
BEGIN
Opened Docx
C:\Users\fake_user\OneDrive\Stuff\f1.docx
After Sys Call
BEGIN
Opened Docx
C:\Users\fake_user\OneDrive\Stuff\f1.docx
After Pass Call
string(5) "fake_user"
System configuration
Windows 7 Professional Edition Service Pack 1
Apache/2.4.26 (Win32)
OpenSSL/1.0.2l
PHP/7.1.7
Python 3.8.1
I tried to run Apache both as a system service and as a user who owns the OneDrive (name changed to "fake_user" here), so it shouldn't be a permissions issue (I think)
Any help appreciated

Running python script with gurobipy module from qt

I want to run a python script from Qt, when the user clicks a button. This script works properly in a terminal but I get an error when I execute from Qt.
I have tried to execute the script from Pycharm IDE and I get the same error:
Traceback (most recent call last):
File "/home/ana/PycharmProjects/Gurobi/one_set.py", line 1, in <module>
from gurobipy import *
File "/usr/local/lib/python2.7/dist-packages/gurobipy/__init__.py", line 1, in <module>
from .gurobipy import *
ImportError: libgurobi81.so: cannot open shared object file: No such file or directory
When I execute "import gurobipy" in a python console, I get no error.
import gurobipy
import pkg_resources
pkg_resources.get_distribution("gurobipy").version
'8.1.1'
Searching libgurobi81.so, I check that this file exists in:
/opt/gurobi811/linux64/lib/libgurobi81.so
/usr/lib/python2.7/dist-packages/gurobi811/linux64/lib/libgurobi81.so
/usr/local/lib/python2.7/dist-packages/gurobipy/libgurobi81.so
As suggested in install instructions, I have included environment variables in /home/usr/.bashrc as:
export GUROBI_HOME="/opt/gurobi811/linux64"
export PATH="${PATH}:${GUROBI_HOME}/bin"
export LD_LIBRARY_PATH="${GUROBI_HOME}/lib"
I also included the other directories that contain libgurobi81.so:
export PATH=$PATH:/usr/lib/python2.7/dist-packages/gurobi811/
export PATH=$PATH:/usr/local/lib/python2.7/dist-packages/gurobipy/
However, from terminal everything works fine and I get the solution:
/usr/bin/python2.7 /home/ana/PycharmProjects/Gurobi/one_set.py
Academic license - for non-commercial use only
instance objVal time
Instance1.csv 0.030176 0.0002670288
[1 rows x 2 columns]
The code I use to run python script from Qt is:
QString command("/usr/bin/python2.7");
QStringList params = QStringList() << "/home/ana/PycharmProjects/Gurobi/one_set.py";
QProcess *process = new QProcess();
process->startDetached(command, params);
process->waitForFinished();
qDebug()<<process->readAllStandardOutput();
process->close();
I expected the same output from Qt as from terminal, since the command I use to run it is the same:
/usr/bin/python2.7 /home/ana/PycharmProjects/Gurobi/one_set.py
Solved. The solution was adding environment variables before the start of the process:
QString command("/usr/bin/python2.7");
QStringList params = QStringList();
params.append("/home/ana/PycharmProjects/Gurobi/one_set.py");
QProcess *process = new QProcess();
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("LD_LIBRARY_PATH", "/usr/local/lib:/opt/gurobi811/linux64/lib:/opt/gurobi811/linux64/lib:/opt/gurobi811/linux64/lib/"); // Add an environment variable
process->setProcessEnvironment(env);
process->start(command, params);
process->waitForFinished();
QString p_stdout = process->readAllStandardOutput();
ui->Output->setText(p_stdout);
process->close();

Pdb error while debugging python app with serverless launched offline

I have problem with debugging my view function with
import pdb; pdb.set_trace()
placed inside it and serverless launched as
> sls offline start
in console.
Namely, making correspondent GET request I receive the following error:
Python: > /.../handler.py(88)get_results()
-> request_params = event.query_params
Python: (Pdb)
Python: 2019-02-20 18:37:43,648 [ERROR] | ...
Traceback (most recent call last):
...
File ".../handler.py", line 88, in get_results
...
File "/usr/lib/python3.6/bdb.py", line 51, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib/python3.6/bdb.py", line 70, in dispatch_line
if self.quitting: raise BdbQuit
bdb.BdbQuit
Google suggests that the problem is in the inability of serverless process to read from stdin, but I don't know how to handle this problem.
Any suggestions?
I found a solution here https://stackoverflow.com/a/26975795/4388451:
create two fifos:
mkfifo fifo_stdin
mkfifo fifo_stdout
in one terminal
In the same terminal open stdout on background, and write to stdin:
cat fifo_stdout & cat > fifo_stdin
In python code create the the pdb object, and use it:
import pdb
mypdb = pdb.Pdb(stdin=open('fifo_stdin', 'r'), stdout=open('fifo_stdout', 'w'))
....
mypdb.set_trace()
Run python code from the folder where fifos were placed (or place fifos in the first step in the folder with python code) in another terminal
Now I am able to use pdb in first console!
PS
It is useful to use --noTimeout option while debugging: sls offline --noTimeout

Using WMI-Client-Wrapper to execute an exe and get output logs

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.

How to know which file is calling which file, filesystem

How to know which file is calling which file in filesystem, like file1.exe is calling file2.exe
so file2.exe is modified,
and file1.exe is entered in log file.
winos
I have searched INTERNET but not able to find any samples.
In order know which file is calling which file you can use the Trace module
exp: if you have 2 files
***file1.py***
import file2
def call1():
file2.call2()
***file2.py***
def call2():
print "---------"
u can use it using console:
$ python -m trace --trackcalls path/to/file1.py
or within a program using a Trace object
****tracefile.py***
import trace,sys
from file1 import call1
#specify what to trace here
tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1)
tracer.runfunc(call1) #call the function call1 in fille1
results = tracer.results()
results.write_results(summary=True, coverdir='.')

Categories