Invoke CTRL+V to an open window - python

I have something in my clipboard, and I'd like to run a python script that invokes CTRL+V as if it was pressed on the keyboard, and pastes the clipboard's content to the current focused window (say chrome). Any idea how to do that?

You have an X-Y problem.
What you want to accomplish is programmatically take data from one program (where you hit cntrl-V) and place it into another arbitrary program (chrome).
There are two ways to do that:
First
You can either set the programs up to have a data exchange mechanism such as a system pipe, or a network connection. This requires some API for data exchange to be already included in the program or access to the source so you might add one. There are very specific channels for cross program data exchange and you wont do well to try to circumvent them. Program A cant just say
get_program_b().get_text_box().add(clip_board);
That would be a violation of Process Isolaton and an OS like windows is written expressly to make it impossible. Some programs are designed to take input from other programs.
popen.open('mysql -e "ISNERT INTO table (a) VALUES ('4')")
Chrome is not one of those programs, chrome avoids allowing programs from doing this because it would be a target for programs to do things like, get the saved password or credit card data out of chrome. Or use save password to login to someone account and buy things in someone elses name.
Second
You could try to spoof user input and input the data exactly like a user would so chrome wont know the difference. But spoofing a user is hard to do and intentionally so because it prevents malicious scripts from taking control of a computer and doing bad things. The makers of windows are accutely aware that spoofing input is a method to circumvent allowed data exchange channels. So the makers of windows made it hard to do. You need to have access to a lot of system assets that most programs wont be given. At a minimum a program has to run as admin on windows to accomplish this, then there are libs that will let you do it. Even then Im willing to bet there are easier way to get the job done. On a machine where you have access to anything and everything it is possible. If you don't have admin access, it should be downright impossible without knowing some unpatched exploit in the system.
Therefore
What you are trying to do goes against what the computer was designed to let you do. If we had more information on what you want to accomplish maybe some of the wonderful people here could help. Getting to the end result you want shouldnt be that hard. But you way of doing it is like trying to run across the ocean, when you just need a boat. As it is my answer is -- dont do it, that's not how windows was designed to work.

Related

Control Program UI Externally

I'll try to be as concise as possible:
Quite some time ago, I started using arduinos and other microcontrollers as custom MIDI devices for my PC.
But now, since I'm into filmmaking, I wanted to create a grading panel for use in Blackmagic's DaVinci Resolve. What i want exactly is to read signals from knobs and slider with a microcontroller and send the data to my PC so that Resolve can use it to apply different adjustments.
Unfortunately, since there are many different adjustments, there are no keyboard shortcuts for them, so I can't just emulate them with the microcontroller.
I have tried to use Cheat Engine to see if those adjustments values where stored somewhere in memory, but I can't seem to find them.
Resolve does have a Python and Lua API, but they're extremely limited and don't offer ANY control over color adjustements anyway.
I know that a few people that had my same idea used another software that mapped MIDI input to mouse movement, but I hate that solution, since the UI not only must be visible at all time, but you also can't change UI elements without needing to 're-calibrate' the mapping software.
To clarify: I'm not asking for code, I'm asking for 'directions'. How can I control a 3rd party software with custom made hardware? (I'm on Windows 10 btw)

Hosting Python Script with I/O in <div> on website

My goal is fairly simple, I have written a python 3 script that runs on an ubuntu server at my workplace. Currently I (and other users) have to SSH into this ubuntu box anytime we want to run the script, which with a growing number of users is getting messy - from a convenience and security standpoint. So my boss would like me to create a nice webpage-based GUI to access this script and some other similar scripts I have written.
This seems like a straight forward thing, but the difficulty is in the details - the script is used for viewing and editing records so it has a lot of back-and-forth communication with the user (using input()) as well as screen clears and code like the following:
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
...to keep things clean and within one terminal.
If absolutely needed of course I could modify the script to accept inputs in a different format and output in a more html-friendly method without line and screen clears, but this would be rather tedious to redo for the whole script. SO - my question is what would be the best way to achieve what I'm after with minimal modifications to my written code? Ideally the webpage would just have a container holding a terminal-like graphic that handles all the input and output of the selected script as if it was running through a full fat terminal.
Things I've already looked into include basic python web frameworks such as CGI or mod_wsgi, or a python package like flask, but - correct me if I'm wrong - it seems there isn't a nice way to handle constant inputs within scripts with these let alone the terminal-oriented clearing I do for clearing lines and screens.
I also looked into ways to just host a full terminal on the webpage, and security concerns aside, this seems like the closest solution - using something like ajaxterm (which seems rather outdated now?) or wetty. My main concern with this is it isn't any easier than just using SSH at that point. Unless I could modify the terminal to auto-login and start a specific script automagically with the push of a button on the webpage, this would just be a glorified web-rendition of putty.
Any suggestions on how you would achieve this?

Multiple desktops with independent mouse/keyboard input

I am working with software that requires only occasional input and that otherwise runs completely in the background.
The input it requires is so simple that I have been able to fully automate it using OpenCV and python. Unfortunately in order to send the input, I need to use mouse events for this, resulting in my mouse being moved around. I tried other ways, such as sending other post_messages directly to the window, but they didn't work unfortunately. So since moving the mouse is the only way to interact, it hinders my productivity, since it will interfere with my daily work. Ideally I would like to use multiple desktops, where the mouse/keyboard inputs are completely separated and where I run all my usual stuff on Desktop 1 and the program & automation on Desktop 2. Doing this seems difficult, however, since there is only one input stream and I would need to have separate input streams which can be controlled individually.
So my question is basically if it is possible to have multiple desktops with independent inputs that can be automated separately?
Please note:
I know there are some solutions that provide input for two mice, but I haven't seen any info on how to interface with them (from python for example), and a lot of them seem to be buggy or discontinued.
I also know that I can use a virtual machine, but unfortunately that is a bit of an overkill, especially given that the underlying program that I want to automate requires quite a bit of resources and those are better used within my primary system.

How to protect my Python program

What I want to do is protect a Python program from being stolen by people with no computer knowledge. I accept the inevitability of the program being pirated, all I want to do is protect it from average users.
I have come up with two ideas.
1.)Set a time restriction by checking online for the date and time. I.E. 10 days from downloaded time.
2.)Checking the IP or Name of the computer that downloaded it and make the program only runs on that computer. (to prevent friends from simply sharing the file).
The problem with both of these is that I'll need to create a .py file "on the fly" and then use something like pytoexe to make it into an .exe so that the user doesn't need to have Python installed.
The problem with the second is that to my understanding ip's change and getting the computer name is a security risk and might scare away users.
So to sum it up, here are my two questions:
1.) Is there a good way in python to only allow the program to run on that single computer?
2.) What is the best way to implement a "on the fly" creation of the exe? (I was going to host the website on my computer and learn php(?)/servers.
I have moderate c/c++ and basic html/css, java, and python experience.
Thank you for your time!
Messy business. You probably already understand that compiled does not mean encrypted.
However, if you're boss considers c-compiled as satisfactory, you can use cython to compile your python code to c-code and then gcc to compile the c-code.
Check here on how to build your setup.py script.
http://docs.cython.org/src/reference/compilation.html#compiling-with-distutils
And you can embed python using into the resulting c code using the --embed option:
# will generate the target.c
$ cython target.py --embed
Give each user a customized installer that has a unique key in it. When it runs, it contacts a server (with the key) and requests the actual program. Server-side, you check if the key is valid and if so, serve the program customized with the key, and mark the key as used. The installer saves the program somewhere the user can access it, and creates a hidden file that contains the key somewhere deep in the bowels of the computer, where the "average user" won't think of looking. When the program is run, the first thing it does is check if the hidden file exists and if it contains the correct key, and refuses to run if not.
(I am assuming that unzipping an executable and reading source code is beyond the ability of the "average user" (read: "grandma"), so using py2exe is ok.)
To avoid having to contact anything on the Internet, you could use the following way to 'dongle' your program:
Take a vital part of your program (something without which the rest won't be useful),
put it into a string,
encrypt that string symmetrically with the MAC address of the computer it shall run on,
then in your program do this:
decrypt that string with the MAC address of the current machine it runs on an and
call that decrypted string using exec.
Example with the vital part being print "hello world":
def getMyMac():
return 123456789L # for testing now
return uuid.getnode() # this would be the real thing
def strxor(s, key):
key *= len(s) / len(key) + 1
return ''.join(chr(ord(key[i]) ^ ord(s[i])) for i in range(len(s)))
def performVitalCode():
code = 'A#ZZA\x16\x15P\\]^\\\x14BYET]\x13'
# I found that code by entering:
# strxor('print "hello world"', str(getMyMac()))
realCode = strxor(code, str(getMyMac()))
exec realCode
I here used a simple xor on strings for crypting (which is not a hard cypher to crack).
Of course the user of the "allowed" computer can hand over his MAC address to the next user which then
either can patch the getMyMac() or
spoof his own MAC address; most network cards allow this.
So this is not a "safe" solution to your problem.
But if a person with just little computer knowledge gave your code to some other guy without any further information (maybe by putting it online in a forum or similar), the receiver won't be able to execute it out of the box.
Finally I need to point out that every chaining of code to a specific computer may well become a hassle for the rightful user of the code. If I'm using a program which stops working just because I switch to a different hardware (maybe just because I get a new laptop), I'm usually pissed and curse the writer of that code. You might not want to annoy your customers.
Seems like a combination of things here. Encapsulating python as others have suggested is a good way to go, for bundling. You may also consider obfuscation, as talked about here in another StackOverflow thread:
Python Code Obfuscation
Which references:
http://freecode.com/projects/pyobfuscate
As for making it so that someone can't just download your program and run it elsewhere or distribute it, how willing are you to inconvenience your end users? :)
As others have noted above, you can generate a compiled and bundled bit of code with the ID specific to the user. That way, if/when the application phones home, you can track usage.
If your end users/customers have the following requirements fulfilled:
An account with you, which they can login and check their subscription/account status
Internet connectivity from the machine running the program
You can make the installation process do the following:
Installer is NOT the full program. Generates a profile of the machine.
This profile bundled up and a hash is generated. Both are uploaded to your servers.
The hash is displayed to the end user to enter, once they have signed into their online web account.
The user installing the application submits the hash, and gets a download link and an unlock key. The key is only good for that dynamically generated download and only on that machine. The downloaded program, however, will accept a range of keys unique to itself(iteratively generated, etc).
The user can then complete the install and run their program. The program will periodically check the profile of the machine it is on, to make sure that the hash does not deviate. If it does, the program can prompt them to login to their web account to generate a new key. The new key is then used to refresh their application. This can be automated by the application, but with the internet laws and such, having the user sign into their account and perhaps agree to any updates to the EULA, would be better.
If they decide to share the program in a VM bundle, they would still need an active account to get keys.
Note, this does not prevent someone from bypassing the hash check. But for the average user, this will serve as a good way for you to deter people giving away or reselling your program.
Just bear in mind, no system is foolproof.

Python: communicating with window application

Im trying to communicate with a windows application with python. Need to fill in text fields and retrieve results (which are also displayed in text fields).
Currently using PywinAuto, works perfectly but its too slow for my purpose. Filling in 6 textfields and pressing two buttons takes 2 to 3 seconds... Im looking for a way to speed this up.
What is the fastest way to control and retrieve data from a windows application, that is feasible for a beginner in Python?
Thanks in advance.
This is very difficult. PywinAuto is one of the best ways to handle this kind of problem, but you have to be very careful about which Windows application you are working with. This is because not every Windows application will "publish" it's controls in a reliable way for you to automate. This is particularly true of Mozilla Firefox. However, the Microsoft Office suite does consistently publish just about every control and button on each of its interfaces that I have ever seen. Thus, the real problem is not with PywinAuto, or even with Windows, it is with whoever wrote the application you are trying to automate and whether or not they reliably publish the interfaces you were trying to control.
The other question you have to ask yourself is how you are populating the text fields and what is actually taking the time. Filling in fields and buttons should take a fraction of a second if they are independently workable. Otherwise, there is probably something else going on that you should investigate.
Good luck. This is a really tough problem.
I have been using pywinauto for 1.5 years. And I have tried lots of different tools for UI automation. You know what, pywinauto not the slowest among them.
Ofcource some actions can take a long tome (seconds), but as a rule it is a high weith actions, such as count children, etc.
Please be sure you do not call findwindows method when it is not realy need.

Categories