#!/usr/bin/env python
"""
ajaxWM - the free web based window manager for remote terminals
Copyright (C) 2007 Dennis Felsing, Andreas Waidler

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

$Id: Ssh.py 76 2007-12-15 11:26:24Z r0q $
"""

#{{{ Imports
import commands

import Singleton
#}}}
class Ssh(Singleton.Singleton):#{{{
    """
Up to now only Dropbear and OpenSSH are supported. If you need
support for another client, just write me a mail and I'll probably build
it in. (Or do it yourself and send me, r0q, a patch.)
    """
    CMD = 'ssh'
    LOGIN = {'dropbear': lambda username, host, port: [Ssh.CMD, '-y', '-l', 
                         username, '-p', port, host],
             'openssh': lambda username, host, port: [Ssh.CMD, '-t', 
                        '-oPreferredAuthentications=' +  
                        'keyboard-interactive,password',  
                        '-oNoHostAuthenticationForLocalhost=yes', 
                        '-oLogLevel=FATAL', '-F/dev/null', '-l', username, 
                        '-p', port, host]}
    #}}}
    def __init__(self, sshCmd = None):#{{{
        if sshCmd:
            Ssh.CMD = sshCmd
    #}}}
    def tryCmd(self):#{{{
        """
Test if the command is valid and the client can be used. Has to be run once.
        """
        returnCode, output = commands.getstatusoutput(Ssh.CMD)
        if returnCode == 32512:
            print options.sshcmd + ' not found'
            return 0

        if output.startswith('Dropbear'):
            Ssh.CLIENT = 'dropbear'
        elif commands.getoutput(Ssh.CMD + ' -v').startswith('OpenSSH'):
            Ssh.CLIENT = 'openssh'
        else:
            print options.sshcmd + ' not compatible'
            return 0
        return 1
    #}}}
    def login(self, username, host, port, cmd = None):#{{{
        r = Ssh.LOGIN[Ssh.CLIENT](username, host, port)
        if cmd: r.append(cmd)
        return r
    #}}}
    def tryLogin(self, username, host, port):#{{{
        return self.login(username, host, port, 'exit')
    #}}}
#}}}
#------------------------------------------------------------------------------
# vim: fdm=marker ts=4 sw=4 expandtab 

