Commit 29e6b5a9 authored by Simon Redman's avatar Simon Redman

Add some helpful helper methods for working with SSH

parent 7966b247
#!/usr/bin/env python3
# Copyright (C) 2018 Simon Redman <sredman@cs.utah.edu>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import getpass
import sys
from pexpect import pxssh
def login_password_failover(session, hostname, username, password=""):
"""
Attempt to log in a pxssh session using only ssh agent-provided public keys, then failover to requesting a password
:param session: non-logged-in session
:param hostname: remote to connect to
:param username: login username
:param password: login password -- Will be prompted for if needed and not passed
:return: password if key-based login failed, otherwise None
"""
# First, try in-memory authentication tools, including the password if it is defined
try:
session.login(hostname, username, password)
return None
except pxssh.ExceptionPxssh:
pass
# That didn't work. Try a password.
original_force_password = session.force_password
session.force_password = True # Probably never necessary -- we already tried key-based login
password = getpass.getpass("Password for {user}@{host}: ".format(user=username, host=hostname))
session.login(hostname, username, password)
session.force_password = original_force_password
return password
def decode_output(session, encoding=sys.stdout.encoding):
"""
Decode the raw bytes written by the SSH session
:param session: pxssh session to read
:param encoding: encoding to use to interpret the output
:return: string-form of the read bytes
"""
return str(session.before.decode(encoding))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment