How to read text from an application window using pywinauto - python-2.7

I have a python code which opens a SSH session using Putty and passes a command to reboot a remote machine using pywinauto.
I want to read the text from the putty terminal after typing the password and compare it
Is there a way I can do it?
Below is the piece of code for the same
app_Putty = application.Application()
app_Putty.start_("C:\Users\debajyoti.bose\Downloads\putty.exe")
app_Putty.top_window_().TypeKeys(IP)
app_Putty.top_window_().TypeKeys("{TAB}"+"22")
app_Putty.top_window_().RadioButton4.Click()
app_Putty.top_window_().OpenButton.Click()
time.sleep(10)
app_Putty.top_window_().NoButton.Click()
time.sleep(2)
app_Putty.top_window_().TypeKeys(user+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys(password+"{ENTER}")
time.sleep(3)
app_Putty.top_window_().TypeKeys("/bin/reboot"+"{ENTER}")
time.sleep(5)
app_Putty.kill_()
time.sleep(120)
I am using pywinauto v0.4.0
Thanks in advance.

OK, let's try app_Putty.top_window_().WindowText(). If it fails your mission looks impossible.

You can't capture directly like this from what I can tell, but I had to find a workaround, and the one I found was this
#clear the buffer with alt space menu
app.window(title='PuTTY - Title').type_keys('% l',with_spaces=True)
#copy the buffer to clipboard
app.window(title='PuTTY - Title').type_keys('% o',with_spaces=True)
I was having to do this because the putty.log file was missing the selection indicator icon (asterisk) on the screen when it was logging output and I needed a way to know which item was selected to move up or down.

Related

Receiving back string of lenght 0 from os.popen('cmd').read()

I am working with a command line tool called 'ideviceinfo' (see https://github.com/libimobiledevice) to help me to quickly get back serial, IMEI and battery health information from the iOS device I work with daily. It executes much quicker than Apple's own 'cfgutil' tools.
Up to know I have been able to develop a more complicated script than the one shown below in PyCharm (my main IDE) to assign specific values etc to individual variables and then to use something like to pyclip and pyautogui to help automatically paste these into the fields of the database app we work with. I have also been able to use the simplified version of the script both in Mac OS X terminal and in the python shell without any hiccups.
I am looking to use AppleScript to help make running the script as easy as possible.
When I try to use Applescript's "do shell script 'python script.py'" I just get back a string of lenght zero when I call 'ideviceinfo'. The exact same thing happens when I try to build an Automator app with a 'Run Shell Script' component for "python script.py".
I have tried my best to isolate the problem down. When other more basic commands such as 'date' are called within the script they return valid strings.
#!/usr/bin/python
import os
ideviceinfoOutput = os.popen('ideviceinfo').read()
print ideviceinfoOutput
print len (ideviceinfoOutput)
boringExample = os.popen('date').read()
print boringExample
print len (boringExample)
I am running Mac OS X 10.11 and am on Python 2.7
Thanks.
I think I've managed to fix it on my own. I just need to be far more explicit about where the 'ideviceinfo' binary (I hope that's the correct term) was stored on the computer.
Changed one line of code to
ideviceinfoOutput = os.popen('/usr/local/bin/ideviceinfo').read()
and all seems to be OK again.

subprocess.popen stream handling

Is it possible to prevent subprocess.popen from showing prompts in the terminal?
Attempting to map a drive but would like to read the prompt for credentials in the script rather than display them to the terminal. The idea being I can carry out actions based on the response.
I am aware the use of shell is frowned upon when using string based commands (for obvious reasons), however I'm controlling the input so am happy with the risk for testing purposes.
I was under the impression that all stdout (interaction) would be parsed into the output_null variable. Instead I am still getting the prompt in the terminal (as illustrated below). I'm either miss understanding how the streams work or I'm missing something. Can anyone enlighten me please
command = "mount -t smbfs //{s}/SYSVOL {m}".format(s=server, m=temp_dir)
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output_null = p.communicate()[0]
if "Password for" in output_null:
print 'awdaa'
Terminal Shows
Password for 192.168.1.111:

When using zeus in zsh cursor position shifts after the the termination of zeus command

Sometimes there is a strange issue with terminal cursor in zsh when zeus command was terminated.
The position of cursor shifts and each line of the output in the console has extra indentation, e.g.
services GET /services(.:format) services#index
payments GET /payments(.:format) payments#index
orders_verify POST /orders_verify(.:format) orders_verify#index
orders GET /orders(.:format) orders#index
diets GET /diets(.:format) diets#index
The only way to fix that is to open a new terminal window/tab
Staircasing is unrelated to locale. Full-screen programs manipulate the terminal-mode settings to let them read single characters from the screen as well as send special characters (such as carriage return and line-feed) to the screen without having the terminal driver "translate" them.
The quick fix — run this command:
reset
(you may have to press controlJ after typing "reset" to enter this properly)
Further reading:
tset, reset - terminal initialization
Make sure you have set LOCALE environment vars to UTF-8 in your .zshrc file
Open .zshrc
vim ~/.zshrc
Add these lines
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
Close the file (Shift-ZZ) and reload it in the current session (or open a new terminal window/tab)
. ~/.zshrc

Python terminal application with interface like nano

This may be a stupid question but I'm not sure how to phrase it in a google-friendly way...
In a terminal if you type something like:
nano some_file
then nano opens up an edit window inside the terminal. A text based application. Ctrl+X closes it again and you see the terminal as it was.
Here's another example:
man ls
How can I make a text based terminal application in python?
I hope this question makes sense, let me know if you need more clarification...
You probably need to use alternative screen buffer. To enable it just print '\0033[?1049h' and for disabling '\0033[?1049l' (Terminal Control Escape Sequences).
http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#The%20Alternate%20Screen%20Buffer
Example:
print('\033[?1049h', end='')
print('Alternative screen buffer')
s = input()
print('\033[?1049l', end='')
print('Normal mode')
print(s) `
This does the trick:
http://docs.python.org/2/howto/curses.html
Example:
import curses
oScreen = curses.initscr()
curses.noecho()
curses.curs_set(0)
oScreen.keypad(1)
oScreen.addstr("Woooooooooooooo\n\n",curses.A_BOLD)
while True:
oEvent = oScreen.getch()
if oEvent == ord("q"):
break
curses.endwin()

Weird Behavior in Windows XP with Python snippet

I wrote a snippet that would automatically copy a file from a source directory to a path on an usb. Because drive letter names are assigned by the PC independent o the slot I figured I would GetLogicalDrives() and if the path to the usb directory is in any of those drives then it would copy (I hope I'm making some sense). Here is the piece of code I wrote in Python:
import itertools, ctypes, string, sys, os.path, shutil
def drive_list():
drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
drive_list = list(itertools.compress(string.ascii_uppercase,
map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
return drive_list
for drive in drive_list():
path = drive + ":\\targer_directory\target_file.ext"
if drive not in ["C", "D", "E"]:
if os.path.exists(path) == True:
shutil.copy2(r'C:\source_directory\source_file.ext', path)
Whenever I run this script I get a bunch of error messages saying:
"Exception Processing Message c0000013 Parameters 75b1bf7c 4 75b1bf7c 75b1bf7c"
I think this probably means that I have some "ghost drives" in my pc. Any help in bypassing this behavior is deeply appreciated.
Note: The code runs at the end and the copy job is done succesfuly, but not until the error messages are cleared which is not the objective if I want to perform automatic backups.
I'm not sure whether this will help or not. But you can try this!
We were receiving the same error on execution of a windows application (an .exe file) and the below steps resolved it.
Goto Registry Editor
(Run -> type 'regedit' -> hit enter)
Expand HKEY_LOCAL_MACHINE
Expand System
Expand CurrentControlSet
Expand Control
Select Windows
Double click on ErrorMode in the right side pane
Set the Value Data as 2
Click OK
Restart your system