Reputation: 2249
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.
Upvotes: 1
Views: 1439
Reputation: 11
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
Upvotes: 1
Reputation: 605
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.
Upvotes: 0
Reputation: 489
a little hackish, but works:
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import subprocess
username = input('username: ')
cmd = ['ssh', '-oStrictHostKeyChecking=no', '%s@server.net' % 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.
Upvotes: 0