Make script executable on OSX? - python

I wrote a little script in python, it basically open a VPN program and then it open a new window in firefox and log in a website. I would like now to avoid launching it from the terminal, and be able to make double click on it(is it called an executable file?). How can I achieve this? I work with python 2.7 on a mac 10.11.1.
I am sorry for eventual mistake but programming is still quite new for me!
import webbrowser
from Quartz.CoreGraphics import *
import subprocess as sp
import time
import pyautogui
def mouseEvent(type, posx, posy):
theEvent = CGEventCreateMouseEvent(None, type, (posx,posy),
kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, theEvent)
def mousemove(posx,posy):
mouseEvent(kCGEventMouseMoved, posx,posy);
def mouseclick(posx,posy):
mouseEvent(kCGEventLeftMouseDown, posx,posy);
mouseEvent(kCGEventLeftMouseUp, posx,posy);
# opening strong VPN
xfoil = sp.Popen(['open', '-a', '/Applications/StrongVPN Client.app'], stdin=sp.PIPE, stdout=sp.PIPE)
time.sleep(5)
mouseclick(900,360);
time.sleep(1)
#open firefox and going to skygo
b = webbrowser.get('firefox')
b.open('http://skygo.sky.it/index.shtml')
time.sleep( 5 )
mouseclick(1010,225);
#clicking on login;
mouseclick(1074,123);
time.sleep( 5 )
mouseclick(830,225);
time.sleep(2)
pyautogui.typewrite('myusername')
time.sleep(1)
#inserting password
mouseclick(830,290);
time.sleep(2)
pyautogui.typewrite('mypassword')
time.sleep(1)
#pressing enter
mouseclick(920,400);
time.sleep(2)
#mousemove(int(currentpos.x),int(currentpos.y)); # Restore mouse position

You can use Automator to wrap a Python script to a normal Mac App bundle that can be opened from OSX GUI.
Better still, what you are trying to achieve can be probably better implemented as set of action in Automator without having to write any Python scripts.

Related

Python SetThreadExecutionState: How do I prevent screen display from turning off?

I am on Windows. I want to run a Python Script that involves keyboard activity hence my PC mustn't lock screen or go to sleep. Instead of changing my PC Sleep Setting, I want to use Python code to keep my Screen Display On for the whole duration of my Python Script.
I modified the code here Prevent sleep mode python (Wakelock on python) but it doesn't work. My screen display still offs automatically. MY modified code as below:
class WindowsInhibitor:
'''Prevent OS sleep/hibernate in windows; code from:
https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
API documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED= 0x00000002
def __init__(self):
pass
def inhibit(self):
import ctypes
print("Preventing Windows from going to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS | \
WindowsInhibitor.ES_DISPLAY_REQUIRED)
def uninhibit(self):
import ctypes
print("Allowing Windows to go to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS)
import os
osSleep = None
# in Windows, prevent the OS from sleeping while we run
if os.name == 'nt':
osSleep = WindowsInhibitor()
osSleep.inhibit()

A trouble with automation of Windows RDP through console

A brief description of my problem:
1.
My Jenkins job is required to establish an RDP connection to another machine to perform some activities.
2.
Until recently, the default password was maintained between sessions. But now some settings have changed, and the password needs to be reentered by hand each time I creating a new RDP session.
I prepared a short python script interacting with the Windows gui via the win32gui package.
I built a stand alone executable file from this script using the pyinstaller.
And finally I added a call to this executable file directly to the job.
Somethig like that:
while attempts:
security_window_title = "Windows Security"
try:
hwnd_credentials = win32gui.FindWindow(0, security_window_title)
window_controls = []
win32gui.EnumChildWindows(hwnd_credentials, collect_window_control, None)
focus_on_window(hwnd_credentials)
sleep(0.5)
prev_user_login = window_controls[2]["hwnd"]
x = int(window_controls[1]["x"] + 80)
y = int(window_controls[1]["y"] + 20)
click(x, y)
type_message(password)
ok_button = window_controls[6]["hwnd"]
push_button(ok_button)
except win32gui.error:
sleep(1)
attempts -= 1
if not attempts:
raise RuntimeError("Can't interact with window: {}.".format(security_window_title))
else:
break
while attempts:
sleep(timeout)
attempts -= 1
if check_connection_started():
break
if check_certificate_errors():
for control in window_controls[::-1]:
if control["text"] == "&Yes":
push_button(control["hwnd"])
if not attempts:
raise RuntimeError("Connection not established.")
3.
This would not be a problem when script running from the job working with the fully functional Windows ui. I can find a window in which my script is supposed to specify a password using the win32gui python package. I can generate all the appropriate keyboard events to enter a password.
Using RDP via console provides me a very strange set of windows-like objects which I can not interact with using the win32gui python package the same way as with ordinary windows. For example, I do locate a window with non zero hwnd and with text property equal to "Remote Desktop Connection". But I can't focus on such a window using the basic method win32gui.SetForegroundWindow(hwnd). This leads to an unnamed win32gui exception.
Is there any possibility to transfer the password to the desired control of the desired window-like structure, so that the job does not interrupt its execution?
Thank you so much for any help.
I can focus on both "Remote Desktop Connection" and "Windows Security" with win32gui.SetForegroundWindow(hwnd).
Sample code:
import win32api
import win32gui
import win32con
import time
from pynput.keyboard import Key, Controller
def main():
Remote = "Remote Desktop Connection"
Security = "Windows Security"
try:
hwnd_Remote = win32gui.FindWindow(0, Remote)
print(hwnd_Remote)
win32gui.ShowWindow(hwnd_Remote,win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(hwnd_Remote)
keyboard = Controller()
keyboard.type('ipaddress')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(3)
hwnd_Security = win32gui.FindWindow(0, Security)
print(hwnd_Security)
win32gui.ShowWindow(hwnd_Security,win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(hwnd_Security)
keyboard.type('password')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
except win32gui.error:
raise RuntimeError("Can't interact with window: {}.".format(Remote))
if __name__ == "__main__":
main()
Make sure that the foreground process did not disable calls to the SetForegroundWindow function. Add the LockSetForegroundWindow(LSFW_UNLOCK) or AllowSetForegroundWindow(ASFW_ANY) to enable the call of SetForegroundWindow.

Best way to kill a task using python

I'm currently trying to use "Taskkill" in Python to kill tasks, but running into several roadblocks. I was wondering if I'm going about this the right way or if there is a better way? Right now the code is not working at all, and just a black dos box appears briefly and goes away. I need to be able to program variables into the task kill, such as i need to be able to use it on my network over a distance. Basically it needs a username (for elevated privileges), The IP Address of the computer I'm connecting to, and the Task that needs the killing. The user name will need a password manually entered.
This is the part of the code:
import tkinter as tk
from tkinter import ttk
from tkinter import *
from socket import *
from subprocess import call
import platform
import os
import sys
import getpass
def kill():
ipad = ipaddress.get()
tsk = tskille.get()
os.system(['taskkill', '/u', 'domain\A'+usrnme, '/s '+ipad, '/F ', '/IM ' +tsk]) # Admin accounts are represeted by an "A" in front of the acctral username.
return
usrnme = getpass.getuser()
tskille = StringVar() # label that can be overwritten manually to whatever
tskille.set("notepad.exe") # Just to put something in the box
ipaddress = StringVar() # have other code to determine the ip address of a pc.
ipaddress.set("0.0.0.0")
Initially i tried using "call" or "runCmd" and finally "os.system" but I'm definitely doing something wrong. Any help would be appreciated
powershell tutorial
To terminate a process using PowerShell, you can either use the WMI interface or use the Stop-Process cmdlet, which comes by default with PowerShell.
Ok so i found out it doesn't like the username part - it will not prompt for a password.. but this part works as intended:
def kill():
usrnme = getpass.getuser()
ipad = ipaddress.get()
tsk = tskille.get()
os.system("taskkill.exe /s %s /F /IM %s" % (ipad, tsk))
return
the getpass.getuser() works as well, basically i just wanted it to be dynamic so that if others use it; it will scan their username and add:
os.system("taskkill.exe /u:domain\A%s /s %s /F /IM %s" % (usrnme, ipad, tsk))
But this code does not work causes the dos window to open and close immediately.

Basic GUI for shell commands with Python Tk threading and os.system calls

I'm doing a basic GUI to provide some user feedback after some shell commands, a little interface for a shell script really.
Showing a TK window, waiting for a os.system call to complete and updating the TK window multiple times, after each os.system call.
How does threading work with tk?
That's it, thanks!
The standard threading library should be perfectly okay if you run it with Tk. This source says, that you should just let the main thread run the gui and create threads for your os.system() calls.
You could write an abstraction like this which updates your GUI upon finishing the task:
def worker_thread(gui, task):
if os.system(str(task)) != 0:
raise Exception("something went wrong")
gui.update("some info")
The thread can be started using thread.start_new_thread(function, args[, kwargs]) from the standard library. See the documentation here.
Just a basic example of what I did, with credit to Constantinius for pointing out that Thread works with Tk!
import sys, thread
from Tkinter import *
from os import system as run
from time import sleep
r = Tk()
r.title('Remote Support')
t = StringVar()
t.set('Completing Remote Support Initalisation ')
l = Label(r, textvariable=t).pack()
def quit():
#do cleanup if any
r.destroy()
but = Button(r, text='Stop Remote Support', command=quit)
but.pack(side=LEFT)
def d():
sleep(2)
t.set('Completing Remote Support Initalisation, downloading, please wait ')
run('sleep 5') #test shell command
t.set('Preparing to run download, please wait ')
run('sleep 5')
t.set("OK thanks! Remote Support will now close ")
sleep(2)
quit()
sleep(2)
thread.start_new_thread(d,())
r.mainloop()

Open a program with python minimized or hidden

What I'm trying to do is to write a script which would open an application only in process list. Meaning it would be "hidden". I don't even know if its possible in python.
If its not possible, I would settle for even a function that would allow for a program to be opened with python in a minimized state maybe something like this:
import subprocess
def startProgram():
subprocess.Hide(subprocess.Popen('C:\test.exe')) # I know this is wrong but you get the idea...
startProgram()
Someone suggested to use win32com.client but the thing is that the program that i want to launch doesn't have a COM server registered under the name.
Any ideas?
It's easy :)
Python Popen Accept STARTUPINFO Structure...
About STARTUPINFO Structure: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331(v=vs.85).aspx
Run Hidden:
import subprocess
def startProgram():
SW_HIDE = 0
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_HIDE
subprocess.Popen(r'C:\test.exe', startupinfo=info)
startProgram()
Run Minimized:
import subprocess
def startProgram():
SW_MINIMIZE = 6
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_MINIMIZE
subprocess.Popen(r'C:\test.exe', startupinfo=info)
startProgram()
You should use win32api and hide your window e.g. using win32gui.EnumWindows you can enumerate all top windows and hide your window
Here is a small example, you may do something like this:
import subprocess
import win32gui
import time
proc = subprocess.Popen(["notepad.exe"])
# lets wait a bit to app to start
time.sleep(3)
def enumWindowFunc(hwnd, windowList):
""" win32gui.EnumWindows() callback """
text = win32gui.GetWindowText(hwnd)
className = win32gui.GetClassName(hwnd)
#print hwnd, text, className
if text.find("Notepad") >= 0:
windowList.append((hwnd, text, className))
myWindows = []
# enumerate thru all top windows and get windows which are ours
win32gui.EnumWindows(enumWindowFunc, myWindows)
# now hide my windows, we can actually check process info from GetWindowThreadProcessId
# http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx
for hwnd, text, className in myWindows:
win32gui.ShowWindow(hwnd, False)
# as our notepad is now hidden
# you will have to kill notepad in taskmanager to get past next line
proc.wait()
print "finished."
What is the purpose?
if you want a hidden(no window) process working in background, best way would be to write a windows service and start/stop it using usual window service mechanism. Windows service can be easily written in python e.g. here is part of my own service (it will not run without some modifications)
import os
import time
import traceback
import pythoncom
import win32serviceutil
import win32service
import win32event
import servicemanager
import jagteraho
class JagteRahoService (win32serviceutil.ServiceFramework):
_svc_name_ = "JagteRaho"
_svc_display_name_ = "JagteRaho (KeepAlive) Service"
_svc_description_ = "Used for keeping important services e.g. broadband connection up"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.stop = False
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.log('stopping')
self.stop = True
def log(self, msg):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,msg))
def SvcDoRun(self):
self.log('folder %s'%os.getcwd())
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
self.start()
def shouldStop(self):
return self.stop
def start(self):
try:
configFile = os.path.join(jagteraho.getAppFolder(), "jagteraho.cfg")
jagteraho.start_config(configFile, self.shouldStop)
except Exception,e:
self.log(" stopped due to eror %s [%s]" % (e, traceback.format_exc()))
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
and you can install it by
python svc_jagteraho.py--startup auto install
and run it by
python python svc_jagteraho.py start
I will be also be seen in services list e.g. services.msc will show it and you can start/stop it else you can use commandline
sc stop jagteraho
Run Hidden:
from subprocess_maximize import Popen
Popen("notepad.exe",show='hidden', priority=0)
Before the code above, use the following command:
pip install subprocess-maximize
If what is appearing is a terminal, redirect the process's stdout.

Categories