SSH Paramiko-Python interactive script-Need to highlight a line from the list and select it - ssh

I am using paramiko for ssh interactive commands. I am able to successfully send all the required commands. I am stuck on one issue. i need somebody help to automate this task.
Issue is on output, i will get 4 options, from this options, i need to move to the required option by using arrow keys and then press enter button to select that option.
Please let me know if anybody knows about this.
import paramiko
import time
import os
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('server',port=22,username='user',password='pass123')
print("connected to the linux machine from windows machine.")
channel=ssh.invoke_shell()
channel_data = str()
while True:
if channel.recv_ready():
channel_data += channel.recv(9999).decode(encoding='utf_8', errors='strict')
os.system('cls')
print("##### Device Output #####")
print("\n",channel_data)
print("\n #####################")
else:
continue
time.sleep(5)
if channel_data.endswith('[root#home ~]# '):
channel.send('somecommand\n')
#highlight and then press enter button to select that option. please help for below code
ifelse channel_data.endswith('I am trying to choose this option from the list'):
channel.send('\n')

We need to send the keycode. for down arrow key, "[B 1b 5b 42" is key code.
Below is the link for complete list of keycode mapping.
http://www.comptechdoc.org/os/linux/howlinuxworks/linux_hlkeycodes.html

Related

oh-my-zsh cursor up before program has finished vs after, how to make them behave consistently

I've noticed that if I press up arrow at a prompt then I get the previous command and up again gets me the command before that.
Whereas if I press up arrow before the previous program has completed then instead I get the previous command displayed, the cursor is at the end of the line, but oh-my-zsh is now in "search for lines that start with ... " mode meaning I can't press up to get the previous command.
I'm sure this behavior is well known and expected but just in case you don't get it you can repo it like this
Type ls return
Type sleep 3 return
wait 3 seconds for prompt to appear
press ⬆ (should show sleep 3)
press ⬆ again (should show ls)
press return (to run ls)
Type sleep 3 return ⬆ (press the up arrow before the 3 seconds elapses)
It should now be showing sleep 3
Press ⬆
it will still be showing sleep 3 but it want it to be showing ls. Instead it is in "search for commands that start with sleep 3 mode instead of just go to previous command mode.
To make try to clear in both cases these are the steps
lsreturn
sleep 3return
⬆
⬆
But they end up with different results depending on if step3 happens before or after step2 finishes.
Note I saw this Q&A: https://unix.stackexchange.com/questions/324623/how-to-make-oh-my-zsh-history-behavior-similar-to-bashs
But that doesn't seem to be what I'm looking for. I like oh-my-zsh's partial line + up = search for lines that start with the partial. What I'm trying to fix is that if I press up on step 2 above it magically inserts a partial where as if I wait until step 2 finishes it doesn't.
How do I get oh-my-zsh to be consistent here so that a premature up arrow behaves the same as a normal up arrow?
I'm surprised this question isn't common. It's seriously infuriating to have the terminal act inconsistently. I'd except most devs using oh-my-zsh to run into this issue all the time and be massively frustrated.
The example above with sleep 3 is only to make it easy to show the problem. In actual usage the problem happens frequently even with short lived commands. I type say git status return git commit somefile -m "short comment" return ⬆⬆ expecting to see "git status". 66% of the time I get git status and the other 34% I get `git commit somefile -m "short comment" and pressing ⬆ again just blinks the cursor and I have to press Ctrl-C to break out of zsh's partial complete mode.
The fact that this does not seem to be a common complaint for oh-my-zsh makes me wonder if I have something setup wrong.
To make it clearer run zsh without oh-my-zsh.
zsh -d -f
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search
Now try the steps above. You'll get consistent behavior.
This might be an overkill solution but, following this guide you can see that you can bind new actions to the up/down arrow key. So if you add:
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down
to your ~/.zshrc, it should remove the functionality you talked about. I managed to get it to work while still maintaining regular search capabilities but this is not thoroughly tested and should probably be used with care.

Generate a ZMK Component only

I have seen the command that generates and also prints the ZMK component. The command is : Generate and Print a ZMK Component for which the Command Code is 'OC'.
But I don't want it to be printed. But in 'OC' command it seems mandatory:
Question:
Is there any way i can tweek this? Or any other command which just generates ZMK without the need to print it? I'm using Thales HSM 9000
from 1270A546-016 Host Command Reference v2.3bNotes:This command is superseded by host command 'A2'.
A printer must be attached to one of the USB ports on the payShield 9000. Serial-to-USB and parallel-to-USB cables are available from Thales, on request.
I believe that there is no way to use the Generate and Print a ZMK Component (OC) command without using a printer.
Follow up
Check the command Generate a Key (A0).
Mode = 0 (Generate key)
Key Type = 000 (Zone Master Key,ZMK)
This is the A0 response using the Thales Test LMK
HEADA100U6809C450D3F68AC78E80BA0C80E1D071F5EE20U6809C450D3F68AC78E80BA0C80E1D071F5EE20

Android MonkeyRunner unable to enter text

I recently started using MonkeyRunner to test the UI of my Android application (I am also using Espresso but wanted to play around with MonkeyRunner). The problem that I am having is that I am unable to enter text into EditText fields using the automation script.
The script navigates through my app perfectly but it doesn't seem to actually enter any text on call of the MonkeyRunner.type() command.
Please find my script below.
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from com.android.monkeyrunner.easy import EasyMonkeyDevice, By
import commands
import sys
import os
# starting the application and test
print "Starting the monkeyrunner script"
# connection to the current device, and return a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
easy_device = EasyMonkeyDevice(device)
apk_path = device.shell('pm path com.mysample
if apk_path.startswith('package:'):
print "application installed."
else:
print "not installed, install APK"
device.installPackage('/MySample/MySample.apk')')
package ="com.mysample"
activity = ".SampleActivity"
print "Package: " + package + "Activity: " + activity
print "starting application...."
device.startActivity(component=package + '/' + activity)
print "...component started"
device.touch(205,361, "DOWN_AND_UP")
device.type("This is sample text")
MonkeyRunner.sleep(1)
result = device.takeSnapshot()
result.writeToFile("images/testimage.png",'png')
As you can see from the script above the text This is sample text should be placed in the EditText box. Both the emulator and screenshot that is taken show no text in the text field.
Am I missing a step or just doing something incorrectly?
Any help would be greatly appreciated!
I would rather use AndroidViewClient/culebra to simplify the task.
Basically, you can connect your device with adb and then run
culebra -VC -d on -t on -o myscript.py
The script obtains references to all of the visible Views. Edit the script and add at the end
no_id10.type('This is sample text')
no_id10.writeImageToFile('/tmp/image.png')
No need to worry about View coordinates, no need to touch and type, no need to add sleeps, etc.
NOTE: this is using no_id10 as an example, the id for your EditText could be different
First of all, I would not use the MonkeyRunner.sleep command, but I would rather use the time package and the time.sleep command. Just import the package
import time
and you should be good to go.
Moreover, I suggest you should wait some time between device.touch and device.type. Try with
device.touch(205,361, "DOWN_AND_UP")
time.sleep(1)
device.type("This is sample text")

Create Dialog Box in Blender using C or Python

How to make a dialog box (three options like quit/OK/Cancel) in blender and processing the text entered through python or in C. I'm unable to find any good tutorial on this. Any help....?
A quick and dirty way is to use zenity command (should be included by default in any python distribution). Try this short example script, it works in my Blender 2.69 on Ubuntu 14.04.
import bpy # bpy or bge does not matter
import subprocess as SP
# call an OS subprocess $ zenity --entry --text "some text"
# (this will ask OS to open a window with the dialog)
res=SP.Popen(['zenity','--entry','--text',
'please write some text'], stdout=SP.PIPE)
# get the user input string back
usertext=str(res.communicate()[0][:-1])
# adjust user input string
text=usertext[2:-1]
print("I got this text from the user: %s"%text)
See the zenity --help for more complex dialogs
blender doesn't offer things like dialogs.
Answers to This previous question on external modules may be helpful.
class DialogOperator(bpy.types.Operator)
bl_idname = "object.dialog_operator"
bl_label = "Save Before You QUIT!"
def execute(self, context):
message = " You didn't saved yet "
self.report({'INFO'}, message)
print(message)
return {'FINISHED'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
class DialogPanel(bpy.types.Panel)
bl_label = "Dialog"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
def draw(self, context):
self.layout.operator("object.dialog_operator")
But this is only for creating a dialog window. after this have to insert buttons in this code.If anyone known this try to post the answer. At the same time I'm also trying to sort out this.

Creating a script for a Telnet session?

Does anyone know of an easy way to create a script that can connect to a telnet server, do some usual telnet stuff, and then log off? I am dealing with users who are not familiar with telnet and the commands they will need to run. All I want is for them to double-click on a script, and have that script automatically execute the commands for them.
You're probably wondering, "What platform are the users on?" They will be on both Windows and Linux. Implementations in languages like Perl, Java, or Python are acceptable. I see that Perl has a Net:: Telnet module. Has anyone used that?
My ideal solution would be to create two script files. a BAT file for windows, and a shell script for Linux. While this would make dual maintenance an issue, it would mean I wouldn't have to install Perl/Java/Python/etc... on every machine. Unfortunately, I have not seen any way to automate a telnet session with batch files or shell scripts.
Thanks.
I've used various methods for scripting telnet sessions under Unix, but the simplest one is probably a sequence of echo and sleep commands, with their output piped into telnet. Piping the output into another command is also a possibility.
Silly example
(echo password; echo "show ip route"; sleep 1; echo "quit" ) | telnet myrouter
This (basically) retrieves the routing table of a Cisco router.
Expect is built for this and can handle the input/output plus timeouts etc. Note that if you're not a TCL fan, there are Expect modules for Perl/Python/Java.
EDIT: The above page suggests that the Wikipedia Expect entry is a useful resource :-)
Another method is to use netcat (or nc, dependent upon which posix) in the same format as vatine shows or you can create a text file that contains each command on it's own line.
I have found that some posix' telnets do not handle redirect correctly (which is why I suggest netcat)
This vbs script reloads a cisco switch, make sure telnet is installed on windows.
Option explicit
Dim oShell
set oShell= Wscript.CreateObject("WScript.Shell")
oShell.Run "telnet"
WScript.Sleep 1000
oShell.Sendkeys "open 172.25.15.9~"
WScript.Sleep 1000
oShell.Sendkeys "password~"
WScript.Sleep 1000
oShell.Sendkeys "en~"
WScript.Sleep 1000
oShell.Sendkeys "password~"
WScript.Sleep 1000
oShell.Sendkeys "reload~"
WScript.Sleep 1000
oShell.Sendkeys "~"
Wscript.Quit
It may not sound a good idea but i used java and used simple TCP/IP socket programming to connect to a telnet server and exchange communication. ANd it works perfectly if you know the protocol implemented. For SSH etc, it might be tough unless you know how to do the handshake etc, but simple telnet works like a treat.
Another way i tried, was using external process in java System.exec() etc, and then let the windows built in telnet do the job for you and you just send and receive data to the local system process.
Check for the SendCommand tool.
You can use it as follows:
perl sendcommand.pl -i login.txt -t cisco -c "show ip route"
import telnetlib
user = "admin"
password = "\r"
def connect(A):
tnA = telnetlib.Telnet(A)
tnA.read_until('username: ', 3)
tnA.write(user + '\n')
tnA.read_until('password: ', 3)
tnA.write(password + '\n')
return tnA
def quit_telnet(tn)
tn.write("bye\n")
tn.write("quit\n")
Couple of questions:
Can you put stuff on the device that you're telnetting into?
Are the commands executed by the script the same or do they vary by machine/user?
Do you want the person clicking the icon to have to provide a userid and/or password?
That said, I wrote some Java a while ago to talk to a couple of IP-enabled power strips (BayTech RPC3s) which might be of use to you. If you're interested I'll see if I can dig it up and post it someplace.
I like the example given by Active State using python. Here is the full link. I added the simple log in part from the link but you can get the gist of what you could do.
import telnetlib
prdLogBox='142.178.1.3'
uid = 'uid'
pwd = 'yourpassword'
tn = telnetlib.Telnet(prdLogBox)
tn.read_until("login: ")
tn.write(uid + "\n")
tn.read_until("Password:")
tn.write(pwd + "\n")
tn.write("exit\n")
tn.close()
Bash shell supports this out-of-box, e.g.
exec {stream}<>/dev/tcp/example.com/80
printf "GET / HTTP/1.1\nHost: example.com\nConnection: close\n\n" >&${stream}
cat <&${stream}
To filter and only show some lines, run: grep Example <&${stream}.
Write the telnet session inside a BAT Dos file and execute.