Without exiting from the ssh_tunnel, open new terminal - python

I am using Python and wxpython for gui. I am trying to connect ssh tunnel. After connecting to ssh, wants a new terminal to open and have to continue my operation in local machine. How to achieve this?
I tried subprocess, pexpect and paramiko, but all are capable to connect to ssh but not open the new teminal
Below my code is there which I tried with pexpect:
import time
import sys
import pexpect
c = pexpect.spawn("ssh -Y -L xxxx:localhost:xxxx user # host.com")
time.sleep(0.1)
c.expect("[pP]aasword")
c.sendline("xxxxxx")
time.sleep(0.2)
c.interact()
c.pexpect([user#host.com~]$)
# here after its connects to ssh then command wont be executed
c.sendline("xfce4-terminal")
On 24/04/2013
I am able to open new terminal but what happens is when the new terminal will open controls from gui doesn't go there. Any help?

Opening a new local terminal and connecting an existing process in to it is a little complicated. There are at least three approaches:
Open the terminal before you start connecting, and run all the code that tries to establish the connection from within it. This is simplest. The main drawback is that the terminal will appear even if the connection fails, which might be what you want to avoid.
Run the connection attempt with a session of tmux or screen and if you detect that it succeeded then reattach that session in to a new terminal.
Make your Python program provide a pty that the terminal can attach to - your program will need to hang around and pass input and output between the remote connection and the pty.

Related

How to read and write directly to the CMD prompt on Windows?

I know others have asked similar questions to this, but what I want to know is whether or not there is a way to simply open a cmd window (on windows 10), leave it open and have a python script automatically type into it.
What I actually need to do is SSH into a remote computer and then from that remote computer, run IDL commands. I have not found a way to do this with subprocess Popen or with Paramiko to SSH. In the case of subprocess, I can't get past authentication to get into the host, i.e. I can't figure out how to type a password in. With Paramiko I am able to get into the remote computer but once there I can't get my IDL code to run, and if it does run it just hangs on that command and won't output anything, even after closing.
It seems to me that rather than sending commands directly to cmd through a subprocess or os command, it would make it much easier if I could just send a string to an open cmd window and have it execute the command and read the result. I'm going through a remote computer and then running IDL code on that remote computer so there are two layers that python has to get through. If I could just write in the cmd terminal it would make my life much easier, rudimentary as it is.
Apologies if I don't have the right lingo with all of this, I'm definitely not a network programmer.
Below is my attempt to use Paramiko. The "ls" command works and the contents of the folder I'm in are printed so I know I've accessed the remote computer, but my idl command does not print anything. Printing the output from the "idl" command itself just causes the program to hang there.
import paramiko
host = "<hostname>"
user = "<myusername>"
password = input("pass:")
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=user, password=password)
_stdin, _stdout,_stderr = client.exec_command("ls", get_pty=True)
print(_stdout.read().decode())
_stdin, _stdout,_stderr = client.exec_command("idl")
_stdin, _stdout,_stderr = client.exec_command("<my command>")
print(_stdout.read().decode())
client.close()
I made much less progress with os and/or subprocess as I can't even get into the remote computer with either of those.

Unable to access pi camera through web browser

I am writing a Python CGI script that I want to run on my laptop's browser. This script will SSH into two Pis, and give the command to take a photo. The server hosting this script is on one of the Pis that I want to SSH into, and that Pi also is acting as an access point for the other Pi and my laptop to connect to (everything is a LAN, not connected to the Internet).
I am successfully able to run this script on my laptop's browser to run simple commands like ls -l on both Pis and print out the results for both on the browser. But, I ultimately want to be able to give the raspistill command to both Pis. When I do this, only the Pi with the server is taking the image, but the other Pi is not. I assume it's because permissions aren't set properly for the server (I tried running the commands as sudo but still no luck). However, if I run the same script on a Python IDLE it works fine. Can somebody help me identify the issue?
Here is my script:
#! /usr/bin/env python3
from pssh import ParallelSSHClient
import cgi
print("Content-Type: text/plain\r\n")
print("\r\n ")
host = ['172.24.1.1','172.24.1.112']
user = 'XXXX'
password = 'XXXX'
client = ParallelSSHClient(host, user, password)
output = client.run_command('raspistill -o test.jpg', sudo=True)
// AMENDMENT:
for line in output['172.24.1.1'].stdout: // works as well with '172.24.1.112'
print(line)
AMENDMENT:
Apparently, if I output anything from the stdout it works fine. Why is this the case? Is is just waiting for me flush the output or something? I suspect this might be a issue with the pssh package I am using.
In your pi, go into the terminal and type sudo raspi-config and then navigate with the keys to camera and then enable it. This will restart you pi.
From https://www.raspberrypi.org/documentation/configuration/camera.md:
Use the cursor keys to move to the camera option, and select 'enable'.
On exiting raspi-config, it will ask to reboot. The enable option
will ensure that on reboot the correct GPU firmware will be running
with the camera driver and tuning, and the GPU memory split is
sufficient to allow the camera to acquire enough memory to run
correctly.
After this, go into sudo raspi-config and enable ssh (which is another option just like pi-camera). Link for this here
After thoroughly reading through the documentation for the pssh module, my problem had to do with the exit codes and how they are handled.
The documentation about run_command states that:
function will return after connection and authentication establishment and after commands have been sent to successfully established SSH channels.
And as a result:
Because of this, exit codes will not be immediately available even for
commands that exit immediately.
Initially, I was just blindly running the run_command expecting the commands to finish, but it turns out I need to get the exit codes to truly finish the processes the commands are running. The documentations states a couple of ways to do this:
At least one of
Iterating over stdout/stderr to completion
Calling client.join(output) is necessary to cause parallel-ssh to wait for commands to finish and be able to gather exit codes.
This is why in my amendment to the code, where I was outputting from stdout, the commands seemed to work properly.

Executing python script without being connected to server

I need to execute python script on remote server (access through puTTY), but I don't have a stable Internet connection, and every time I execute the script I get problems after several minutes due to my Internet getting disconnected.
How do I remotely execute the script without being connected to server?
(e.g. I connect to server, run script, and can logout while executing)
You can use a Linux Screen, it opens a background terminal and keeps a shell active even through network disruptions.
Open the screen typing in your terminal $ screen and execute there your script, even if you lose connection it won't kill the process.
Here you will find a well explained How to for this program. I use it for my regular day working on remote.
try this
nohup your_script >/dev/null 2>&1 &
program will be running in background

Pipe PuTTY console to Python script

I am trying to launch a PuTTY window that establishes a serial connection, and then have the main cmd window (the one that launched my Python script) control the PuTTY window. The PuTTY window will still be open and showing everything, but I want to disable the stdin on it and just have it get the input from the cmd shell.
So I have it successfully launching the PuTTY window, just cant seem to pipe my outputs and inputs like I want. Any help would be greatly appreciated!
Code for launching PuTTY window:
pty=subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
PuTTY is a GUI application. It is not designed for automation.
For automation, use the Plink, PuTTY command-line utility. It is a console application, so it reads commands from its standard-input.
See:
Using the command-line connection tool Plink.
Run Unix commands using PuTTY in C#
PuTTY (note case) is a GUI program and has nothing what so ever to do with cmd prompts.
I use PuTTY all day and out of a lot of people (my coy has 175,000 employees but most wouldn't use PuTTY) I'm the only one that automates it. I use VBScript sendkeys bound to hotkeys in windows shortcuts (must be on desktop or start menu).
PuTTY does have a command line version with a similar name, but I've not used it.

How to continuously run a Python script on an EC2 server?

I've setup an Amazon EC2 server. I have a Python script that is supposed to download large amounts of data from the web onto the server. I can run the script from the terminal through ssh, however very often I loose the ssh connection. When I loose the connection, the script stops.
Is there a method where I tell the script to run from terminal and when I disconnect, the script is still running on the server?
You have a few options.
You can add your script to cron to be run regularly.
You can run your script manually, and detach+background it using nohup.
You can run a tool such as GNU Screen, and detach your terminal and log out, only to continue where you left off later. I use this a lot.
For example:
Log in to your machine, run: screen.
Start your script and either just close your terminal or properly detach your session with: Ctrl+A, D, D.
Disconnect from your terminal.
Reconnect at some later time, and run screen -rD. You should see your stuff just as you left it.
You can also add your script to /etc/rc.d/ to be invoked on book and always be running.
You can also use nohup to make your script run in the background or when you have disconnected from your session:
nohup script.py &
The & at the end of the command explicitly tells nohup to run your script in the background.
If it just a utility you run ad-hoc, not a service daemon of some kind, i would just run it in screen. Than you can disconnect if you want and open the terminal back up later... Or reconnect the terminal if you get disconnected. It should be in your linux distros package manager. Just search for screen
http://www.gnu.org/software/screen/
nohup runs the given command with hangup signals ignored, so that the command can continue running in the background after you log out.
Syntax:
nohup Command [Arg]...
Example:
nohup example.py
nohup rasa run
Also, you can run scripts continuously using the cron command.
For more:
https://ss64.com/bash/nohup.html
https://opensource.com/article/17/11/how-use-cron-linux

Categories

Resources