1

I am writing a little script which picks the best machine out of a few dozen to connect to. It gets a users name and password, and then picks the best machine and gets a hostname. Right now all the script does is print the hostname. What I want is for the script to find a good machine, and open an ssh connection to it with the users provided credentials.

So my question is how do I get the script to open the connection when it exits, so that when the user runs the script, it ends with an open ssh connection.

I am using sshpass.

3
  • Why do you want to exit? The best you could hope for is an open ssh connection and the local shell battling for terminal input... if its even possible at all. Why not just use subprocess.call, without setting up pipes for stdin/out/err and run the ssh connection within python? Commented Mar 10, 2015 at 18:48
  • Turns out I was thinking about how to accomplish my task wrong. I was stuck on having my script opening an ssh connection, when what I should have been doing was using the script to print credentials and pipe them into the ssh command. Commented Mar 11, 2015 at 23:40
  • that's a good solution... although just having the script run the ssh session without exiting likely requires less of a learning curve for your users. Commented Mar 12, 2015 at 0:02

3 Answers 3

1

You can use the os.exec* function to replace the Python process with the callee:

import os
os.execl("/usr/bin/ssh", "user@host", ...)

https://docs.python.org/2/library/os.html#os.execl

Sign up to request clarification or add additional context in comments.

Comments

0

If you want the python script to exit, I think your best bet would be to continue doing a similar thing to what you're doing; print the credentials in the form of arguments to the ssh command and run python myscript.py | xargs ssh. As tdelaney pointed out, though, subprocess.call(['ssh', args]) will let you run the ssh shell as a child of your python process, causing python to exit when the connection is closed.

1 Comment

Thanks, I was thinking about how to do what I wanted to do all wrong.
0

a little hackish, but works:

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import subprocess

username = input('username: ')

cmd = ['ssh', '-oStrictHostKeyChecking=no', '%[email protected]' % username,]
subprocess.call(cmd)

In this example I'm not using sshpass, but the idea with sshpass is the same as using ssh. Use subprocess.call to call the ssh part.

EDIT: Now I realized you want to exit the python process first. In my answer the process dies when the ssh connection is gone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.