How to escape a python interactive shell - python

I am trying to escape a python interactive shell within an ssh server without closing the ssh connection, using exit(), quit() ctrl D closes the ssh connection

I'm assuming your connection is to a Linux/Unix server. If it's Windows, this won't help.
If you only close the python interpreter (ctrl-c for instance) it shouldn't close the SSH connection, since the python interpreter is running on top of the unix shell, which you are actually connected to.
The best way (or at least the easiest) to keep your SSH connection and keep any program running after you leave is to use a tool like tmux or screen (if your linux machine does not have tmux installed).
In order to do so, you can either start your program with $ screen python or start screen before you run anything, and it will start a screen session with bash running.
Then you can safely close the ssh connection, and, when you ssh back into the machine, use screen -r to return to where you leave.

You can easily import the pty module
import pty
and then spawn a new bash shell "/bin/bash" with the module using
pty.spawn("/bin/bash")
Note: "bash" in this context can be changed depending on what shell is avaliable on the server which could be "sh", "dash" or any other type of unix compatible shell

ssh -t
-t flag forces use of ptty. Control sequences will be sent directly to remote process

Related

Running Python Script on Remote Server via SSH

I am trying to run this Python Script on a Digital Ocean (DO) Droplet (Ubuntu 16):
https://github.com/instabot-py/instabot.py
Although I can run python3 example.py the process stops if I kill the Terminal windown I used to SSH into the DO Droplet.
Is there a way to run this Python script and disconnect from the DO Droplet with the Python script still running?
Use nohup to run program in background
nohup python3 example.py > /dev/null 2>&1 &
Or you can use screen to do this:
$ screen
$ python3 example.py
To detach the current session, you can press Ctrl+A and then press D.
To re-attach previous session, use command `screen -r`
The screen command is more powerful than nohup.
You can use screen in linux to continue executing the process in background even after you disconnect from server.
Similarly tmux can be used.
The answer to this question is most probably what you are looking for.
You can try these python library to achieve this
http://www.paramiko.org/
https://pypi.python.org/pypi/spur
Or you can also use tmux to run command on remote server and your tmux seisson will run in the background even if you quit the shell. You can join that tmux session even after days and continue executing command
We use the following format to execute remote script
ssh -t -t user#host.com 'nohup /path/to/scrip.py'

Python script to connect via ssh, run process and disconnect without waiting

I have a problem with running non finishing process via ssh from python script. What I need to do:
Connect to remote server via ssh
Run mongod on this server
Finish script execution without killing mongod process
For now, I'm using subprocess.Popen in this way:
subprocess.Popen(['ssh', 'user#' + host, 'mongod', '-f', '/temp-mongo.conf', '&'])
Problem is that script ends before I'm asked about user password, so it finishes with Too many authentication failures for root.
I tried to use p = subprocess.Popen(...).communicate() and it'a almost ok, but then script waits for mongod command to be finished, what obviously won't happen.
What is proper way to do this? Can I do something to pass password automatically?
I agree with e4c5 that you should use a tool like Fabric for that. If you want to stay with the dirty way something like this should work:
subprocess.call('ssh user#%s "mongod -f /temp-mongo.conf &>/dev/null &"' % host,
shell=True)
Note that you need to do:
quotes around the remote call
add &>/dev/null which routes all output of mongod to /dev/null (without this it will block, not 100% sure why. Probably since the stdout of the shell is attached to the command)
use shell=True so the shell builds up the command for you (so you don't need to put a ", " instead of each space)
This also works with auth over public key (instead of writing the password by hand)
The proper way for SSH without having to enter passwords is to use public key authentication.
I would also look at Fabric for running commands via SSH.
And you aren't running the command in a shell environment on the server. If you run
ssh host ls &
the & will actually put ssh in the background, not ls on the host. Instead try doing
ssh host sh -c 'ls &'

ssh session as python subprocess takes input but does not print it to stdout

I'm trying use python's cmd library to create a shell with limited commands. One requirement I have is to be able to run a command that executes an existing shell script which opens an ssh session on a remote machine and from there allows the user to interact with the remote shell as if it was a regular ssh session.
Simply using subprocess.Popen('[/path/to/connect.sh]') works well at least as a starting point except for one issue. You can interact with the remote shell but the input that you type is not shown on stdout...so for example you see the prompt on your stdout but when you type 'ls' you don't see it being typed but when you hit return it works as expected.
I'm trying to wrap my head around how to print the input to stdout and still send it along to the remote ssh session.
EDIT:
Actual code without using cmd was just the one line:
ssh_session = subprocess.Popen(['connect.sh'])
it was fired from a do_* method in a class which extended cmd.Cmd. I think I may end up using paramiko but would still be interested in anyone's input on this.
Assuming you are using a Unix like system, SSH detects if you are on a terminal or not. When it detects that you are not on a terminal, like when using subprocess, it will not echo the characters typed. Instead you might want to use a pseudo-terminal, see pexpect, or pty. This way you can get the output from SSH as if it was running on a true terminal.

run ssh command remotely without redirecting output

I want to run a python script on my server (that python script has GUI). But I want to start it from ssh. Something like this:
ssh me#server -i my_key "nohup python script.py"
... > let the script run forever
BUT it complains "unable to access video driver" since it is trying to use my ssh terminal as output.
Can I somehow make my commands output run on server machine and not to my terminal... Basically something like "wake-on-lan functionality" -> tell the server you want something and he will do everything using its own system (not sending any output back)
What about
ssh me#server -i my_key "nohup python script.py >/dev/null 2>&1"
You can use redirection to some remote logfile instead of /dev/null of course.
? :)
EDIT: GUI applications on X usually use $DISPLAY variable to know where they should be displayed. Moreover, X11 display servers use authorization to permit or disallow applications connecting to its display. Commands
export DISPLAY=:0 && xhost +
may be helpful for you.
Isn't it possible for you to rather use python ssh extension instead of calling external application?
It would:
run as one process
guarantee that invocation will be the same among all possible system
lose the overhead from "execution"
send everything trough ssh (you won't have to worry about input like "; possibly local executed command)
If not, go with what Piotr Wades suggested.

Execute remote python script via SSH

I want to execute a Python script on several (15+) remote machine using SSH. After invoking the script/command I need to disconnect ssh session and keep the processes running in background for as long as they are required to.
I have used Paramiko and PySSH in past so have no problems using them again. Only thing I need to know is how to disconnect a ssh session in python (since normally local script would wait for each remote machine to complete processing before moving on).
This might work, or something similar:
ssh user#remote.host nohup python scriptname.py &
Basically, have a look at the nohup command.
On Linux machines, you can run the script with 'at'.
echo "python scriptname.py" ¦ at now
If you are going to perform repetitive tasks on many hosts, like for example deploying software and running setup scripts, you should consider using something like Fabric
Fabric is a Python (2.5 or higher) library and command-line tool for
streamlining the use of SSH for application deployment or systems
administration tasks.
It provides a basic suite of operations for executing local or remote
shell commands (normally or via sudo) and uploading/downloading files,
as well as auxiliary functionality such as prompting the running user
for input, or aborting execution.
Typical use involves creating a Python module containing one or more
functions, then executing them via the fab command-line tool.
You can even use tmux in this scenario.
As per the tmux documentation:
tmux is a terminal multiplexer. It lets you switch easily between several programs in one terminal, detach them (they keep running in the background) and reattach them to a different terminal. And do a lot more
From a tmux session, you can run a script, quit the terminal, log in again and check back as it keeps the session until the server restart.
How to configure tmux on a cloud server

Categories