Ejemplo n.º 1
0
    def test_userAtHost(self):
        """
        CompleteUserAtHost produces zsh shell-code that completes hostnames or
        a word of the form <username>@<hostname>.
        """
        c = usage.CompleteUserAtHost()
        out = c._shellCode('some-option', usage._ZSH)
        self.assertTrue(out.startswith(':host | user@host:'))

        c = usage.CompleteUserAtHost(descr='some action', repeat=True)
        out = c._shellCode('some-option', usage._ZSH)
        self.assertTrue(out.startswith('*:some action:'))
Ejemplo n.º 2
0
class ClientOptions(options.ConchOptions):

    synopsis = """Usage:   cftp [options] [user@]host
         cftp [options] [user@]host[:dir[/]]
         cftp [options] [user@]host[:file [localfile]]
"""
    longdesc = ("cftp is a client for logging into a remote machine and "
                "executing commands to send and receive file information")

    optParameters = [
                    ['buffersize', 'B', 32768, 'Size of the buffer to use for sending/receiving.'],
                    ['batchfile', 'b', None, 'File to read commands from, or \'-\' for stdin.'],
                    ['requests', 'R', 5, 'Number of requests to make before waiting for a reply.'],
                    ['subsystem', 's', 'sftp', 'Subsystem/server program to connect to.']]

    compData = usage.Completions(
        descriptions={
            "buffersize": "Size of send/receive buffer (default: 32768)"},
        extraActions=[usage.CompleteUserAtHost(),
                      usage.CompleteFiles(descr="local file")])

    def parseArgs(self, host, localPath=None):
        self['remotePath'] = ''
        if ':' in host:
            host, self['remotePath'] = host.split(':', 1)
            self['remotePath'].rstrip('/')
        self['host'] = host
        self['localPath'] = localPath
Ejemplo n.º 3
0
class ClientOptions(options.ConchOptions):

    synopsis = """Usage:   cftp [options] [user@]host
         cftp [options] [user@]host[:dir[/]]
         cftp [options] [user@]host[:file [localfile]]
"""
    longdesc = (
        "cftp is a client for logging into a remote machine and "
        "executing commands to send and receive file information"
    )

    optParameters: List[List[Optional[Union[str, int]]]] = [
        ["buffersize", "B", 32768, "Size of the buffer to use for sending/receiving."],
        ["batchfile", "b", None, "File to read commands from, or '-' for stdin."],
        ["requests", "R", 5, "Number of requests to make before waiting for a reply."],
        ["subsystem", "s", "sftp", "Subsystem/server program to connect to."],
    ]

    compData = usage.Completions(
        descriptions={"buffersize": "Size of send/receive buffer (default: 32768)"},
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.CompleteFiles(descr="local file"),
        ],
    )

    def parseArgs(self, host, localPath=None):
        self["remotePath"] = ""
        if ":" in host:
            host, self["remotePath"] = host.split(":", 1)
            self["remotePath"].rstrip("/")
        self["host"] = host
        self["localPath"] = localPath
Ejemplo n.º 4
0
class ClientOptions(ConchOptions):

    synopsis = """Usage:   conch [options] host [command]
"""
    longdesc = ("conch is a SSHv2 client that allows logging into a remote "
                "machine and executing commands.")

    optParameters = [
        ["escape", "e", "~"],
        [
            "localforward",
            "L",
            None,
            "listen-port:host:port   Forward local port to remote address",
        ],
        [
            "remoteforward",
            "R",
            None,
            "listen-port:host:port   Forward remote port to local address",
        ],
    ]

    optFlags = [
        ["null", "n", "Redirect input from /dev/null."],
        ["fork", "f", "Fork to background after authentication."],
        ["tty", "t", "Tty; allocate a tty even if command is given."],
        ["notty", "T", "Do not allocate a tty."],
        ["noshell", "N", "Do not execute a shell or command."],
        ["subsystem", "s", "Invoke command (mandatory) as SSH2 subsystem."],
    ]

    compData = usage.Completions(
        mutuallyExclusive=[("tty", "notty")],
        optActions={
            "localforward": usage.Completer(descr="listen-port:host:port"),
            "remoteforward": usage.Completer(descr="listen-port:host:port"),
        },
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.Completer(descr="command"),
            usage.Completer(descr="argument", repeat=True),
        ],
    )

    localForwards: List[Tuple[int, Tuple[int, int]]] = []
    remoteForwards: List[Tuple[int, Tuple[int, int]]] = []

    def opt_escape(self, esc):
        """
        Set escape character; ``none'' = disable
        """
        if esc == "none":
            self["escape"] = None
        elif esc[0] == "^" and len(esc) == 2:
            self["escape"] = chr(ord(esc[1]) - 64)
        elif len(esc) == 1:
            self["escape"] = esc
        else:
            sys.exit(f"Bad escape character '{esc}'.")

    def opt_localforward(self, f):
        """
        Forward local port to remote address (lport:host:port)
        """
        localPort, remoteHost, remotePort = f.split(":")  # Doesn't do v6 yet
        localPort = int(localPort)
        remotePort = int(remotePort)
        self.localForwards.append((localPort, (remoteHost, remotePort)))

    def opt_remoteforward(self, f):
        """
        Forward remote port to local address (rport:host:port)
        """
        remotePort, connHost, connPort = f.split(":")  # Doesn't do v6 yet
        remotePort = int(remotePort)
        connPort = int(connPort)
        self.remoteForwards.append((remotePort, (connHost, connPort)))

    def parseArgs(self, host, *command):
        self["host"] = host
        self["command"] = " ".join(command)
Ejemplo n.º 5
0
class ClientOptions(options.ConchOptions):

    synopsis = """Usage:   conch [options] host [command]
"""
    longdesc = ("conch is a SSHv2 client that allows logging into a remote "
                "machine and executing commands.")

    optParameters = [
        ['escape', 'e', '~'],
        [
            'localforward', 'L', None,
            'listen-port:host:port   Forward local port to remote address'
        ],
        [
            'remoteforward', 'R', None,
            'listen-port:host:port   Forward remote port to local address'
        ],
    ]

    optFlags = [
        ['null', 'n', 'Redirect input from /dev/null.'],
        ['fork', 'f', 'Fork to background after authentication.'],
        ['tty', 't', 'Tty; allocate a tty even if command is given.'],
        ['notty', 'T', 'Do not allocate a tty.'],
        ['noshell', 'N', 'Do not execute a shell or command.'],
        ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
    ]

    compData = usage.Completions(
        mutuallyExclusive=[("tty", "notty")],
        optActions={
            "localforward": usage.Completer(descr="listen-port:host:port"),
            "remoteforward": usage.Completer(descr="listen-port:host:port")
        },
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.Completer(descr="command"),
            usage.Completer(descr="argument", repeat=True)
        ])

    localForwards = []
    remoteForwards = []

    def opt_escape(self, esc):
        """
        Set escape character; ``none'' = disable
        """
        if esc == 'none':
            self['escape'] = None
        elif esc[0] == '^' and len(esc) == 2:
            self['escape'] = chr(ord(esc[1]) - 64)
        elif len(esc) == 1:
            self['escape'] = esc
        else:
            sys.exit("Bad escape character '{}'.".format(esc))

    def opt_localforward(self, f):
        """
        Forward local port to remote address (lport:host:port)
        """
        localPort, remoteHost, remotePort = f.split(':')  # Doesn't do v6 yet
        localPort = int(localPort)
        remotePort = int(remotePort)
        self.localForwards.append((localPort, (remoteHost, remotePort)))

    def opt_remoteforward(self, f):
        """
        Forward remote port to local address (rport:host:port)
        """
        remotePort, connHost, connPort = f.split(':')  # Doesn't do v6 yet
        remotePort = int(remotePort)
        connPort = int(connPort)
        self.remoteForwards.append((remotePort, (connHost, connPort)))

    def parseArgs(self, host, *command):
        self['host'] = host
        self['command'] = ' '.join(command)
Ejemplo n.º 6
0
class ConchOptions(usage.Options):

    optParameters = [
        ['user', 'l', None, 'Log in using this user name.'],
        ['identity', 'i', None],
        ['ciphers', 'c', None],
        ['macs', 'm', None],
        [
            'port', 'p', None,
            'Connect to this port.  Server must be on the same port.'
        ],
        ['option', 'o', None, 'Ignored OpenSSH options'],
        ['host-key-algorithms', '', None],
        ['known-hosts', '', None, 'File to check for host keys'],
        [
            'user-authentications', '', None,
            'Types of user authentications to use.'
        ],
        ['logfile', '', None, 'File to log to, or - for stdout'],
    ]  # type: List[List[Optional[Union[str, int]]]]

    optFlags = [
        ['version', 'V', 'Display version number only.'],
        ['compress', 'C', 'Enable compression.'],
        ['log', 'v', 'Enable logging (defaults to stderr)'],
        ['nox11', 'x', 'Disable X11 connection forwarding (default)'],
        ['agent', 'A', 'Enable authentication agent forwarding'],
        ['noagent', 'a', 'Disable authentication agent forwarding (default)'],
        [
            'reconnect', 'r',
            'Reconnect to the server if the connection is lost.'
        ],
    ]

    compData = usage.Completions(
        mutuallyExclusive=[("agent", "noagent")],
        optActions={
            "user":
            usage.CompleteUsernames(),
            "ciphers":
            usage.CompleteMultiList(SSHCiphers.cipherMap.keys(),
                                    descr='ciphers to choose from'),
            "macs":
            usage.CompleteMultiList(SSHCiphers.macMap.keys(),
                                    descr='macs to choose from'),
            "host-key-algorithms":
            usage.CompleteMultiList(
                SSHClientTransport.supportedPublicKeys,
                descr='host key algorithms to choose from'),
            #"user-authentications": usage.CompleteMultiList(?
            # descr='user authentication types' ),
        },
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.Completer(descr="command"),
            usage.Completer(descr='argument', repeat=True)
        ])

    def __init__(self, *args, **kw):
        usage.Options.__init__(self, *args, **kw)
        self.identitys = []
        self.conns = None

    def opt_identity(self, i):
        """Identity for public-key authentication"""
        self.identitys.append(i)

    def opt_ciphers(self, ciphers):
        "Select encryption algorithms"
        ciphers = ciphers.split(',')
        for cipher in ciphers:
            if cipher not in SSHCiphers.cipherMap:
                sys.exit("Unknown cipher type '%s'" % cipher)
        self['ciphers'] = ciphers

    def opt_macs(self, macs):
        "Specify MAC algorithms"
        if isinstance(macs, unicode):
            macs = macs.encode("utf-8")
        macs = macs.split(b',')
        for mac in macs:
            if mac not in SSHCiphers.macMap:
                sys.exit("Unknown mac type '%r'" % mac)
        self['macs'] = macs

    def opt_host_key_algorithms(self, hkas):
        "Select host key algorithms"
        if isinstance(hkas, unicode):
            hkas = hkas.encode("utf-8")
        hkas = hkas.split(b',')
        for hka in hkas:
            if hka not in SSHClientTransport.supportedPublicKeys:
                sys.exit("Unknown host key type '%r'" % hka)
        self['host-key-algorithms'] = hkas

    def opt_user_authentications(self, uas):
        "Choose how to authenticate to the remote server"
        if isinstance(uas, unicode):
            uas = uas.encode("utf-8")
        self['user-authentications'] = uas.split(b',')
Ejemplo n.º 7
0
class GeneralOptions(usage.Options):
    synopsis = """Usage:    tkconch [options] host [command]
 """

    optParameters = [['user', 'l', None, 'Log in using this user name.'],
                    ['identity', 'i', '~/.ssh/identity', 'Identity for public key authentication'],
                    ['escape', 'e', '~', "Set escape character; ``none'' = disable"],
                    ['cipher', 'c', None, 'Select encryption algorithm.'],
                    ['macs', 'm', None, 'Specify MAC algorithms for protocol version 2.'],
                    ['port', 'p', None, 'Connect to this port.  Server must be on the same port.'],
                    ['localforward', 'L', None, 'listen-port:host:port   Forward local port to remote address'],
                    ['remoteforward', 'R', None, 'listen-port:host:port   Forward remote port to local address'],
                    ]

    optFlags = [['tty', 't', 'Tty; allocate a tty even if command is given.'],
                ['notty', 'T', 'Do not allocate a tty.'],
                ['version', 'V', 'Display version number only.'],
                ['compress', 'C', 'Enable compression.'],
                ['noshell', 'N', 'Do not execute a shell or command.'],
                ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
                ['log', 'v', 'Log to stderr'],
                ['ansilog', 'a', 'Print the received data to stdout']]

    _ciphers = transport.SSHClientTransport.supportedCiphers
    _macs = transport.SSHClientTransport.supportedMACs

    compData = usage.Completions(
        mutuallyExclusive=[("tty", "notty")],
        optActions={
            "cipher": usage.CompleteList(_ciphers),
            "macs": usage.CompleteList(_macs),
            "localforward": usage.Completer(descr="listen-port:host:port"),
            "remoteforward": usage.Completer(descr="listen-port:host:port")},
        extraActions=[usage.CompleteUserAtHost(),
                      usage.Completer(descr="command"),
                      usage.Completer(descr="argument", repeat=True)]
        )

    identitys = []  # type: List[str]
    localForwards = []  # type: List[Tuple[int, Tuple[int, int]]]
    remoteForwards = []  # type: List[Tuple[int, Tuple[int, int]]]

    def opt_identity(self, i):
        self.identitys.append(i)

    def opt_localforward(self, f):
        localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
        localPort = int(localPort)
        remotePort = int(remotePort)
        self.localForwards.append((localPort, (remoteHost, remotePort)))

    def opt_remoteforward(self, f):
        remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
        remotePort = int(remotePort)
        connPort = int(connPort)
        self.remoteForwards.append((remotePort, (connHost, connPort)))

    def opt_compress(self):
        SSHClientTransport.supportedCompressions[0:1] = ['zlib']

    def parseArgs(self, *args):
        if args:
            self['host'] = args[0]
            self['command'] = ' '.join(args[1:])
        else:
            self['host'] = ''
            self['command'] = ''
Ejemplo n.º 8
0
class GeneralOptions(usage.Options):
    synopsis = """Usage:    tkconch [options] host [command]
 """

    optParameters = [
        ["user", "l", None, "Log in using this user name."],
        [
            "identity", "i", "~/.ssh/identity",
            "Identity for public key authentication"
        ],
        ["escape", "e", "~", "Set escape character; ``none'' = disable"],
        ["cipher", "c", None, "Select encryption algorithm."],
        ["macs", "m", None, "Specify MAC algorithms for protocol version 2."],
        [
            "port", "p", None,
            "Connect to this port.  Server must be on the same port."
        ],
        [
            "localforward",
            "L",
            None,
            "listen-port:host:port   Forward local port to remote address",
        ],
        [
            "remoteforward",
            "R",
            None,
            "listen-port:host:port   Forward remote port to local address",
        ],
    ]

    optFlags = [
        ["tty", "t", "Tty; allocate a tty even if command is given."],
        ["notty", "T", "Do not allocate a tty."],
        ["version", "V", "Display version number only."],
        ["compress", "C", "Enable compression."],
        ["noshell", "N", "Do not execute a shell or command."],
        ["subsystem", "s", "Invoke command (mandatory) as SSH2 subsystem."],
        ["log", "v", "Log to stderr"],
        ["ansilog", "a", "Print the received data to stdout"],
    ]

    _ciphers = transport.SSHClientTransport.supportedCiphers
    _macs = transport.SSHClientTransport.supportedMACs

    compData = usage.Completions(
        mutuallyExclusive=[("tty", "notty")],
        optActions={
            "cipher": usage.CompleteList([v.decode() for v in _ciphers]),
            "macs": usage.CompleteList([v.decode() for v in _macs]),
            "localforward": usage.Completer(descr="listen-port:host:port"),
            "remoteforward": usage.Completer(descr="listen-port:host:port"),
        },
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.Completer(descr="command"),
            usage.Completer(descr="argument", repeat=True),
        ],
    )

    identitys: List[str] = []
    localForwards: List[Tuple[int, Tuple[int, int]]] = []
    remoteForwards: List[Tuple[int, Tuple[int, int]]] = []

    def opt_identity(self, i):
        self.identitys.append(i)

    def opt_localforward(self, f):
        localPort, remoteHost, remotePort = f.split(":")  # doesn't do v6 yet
        localPort = int(localPort)
        remotePort = int(remotePort)
        self.localForwards.append((localPort, (remoteHost, remotePort)))

    def opt_remoteforward(self, f):
        remotePort, connHost, connPort = f.split(":")  # doesn't do v6 yet
        remotePort = int(remotePort)
        connPort = int(connPort)
        self.remoteForwards.append((remotePort, (connHost, connPort)))

    def opt_compress(self):
        SSHClientTransport.supportedCompressions[0:1] = ["zlib"]

    def parseArgs(self, *args):
        if args:
            self["host"] = args[0]
            self["command"] = " ".join(args[1:])
        else:
            self["host"] = ""
            self["command"] = ""
Ejemplo n.º 9
0
class ConchOptions(usage.Options):

    optParameters: List[List[Optional[Union[str, int]]]] = [
        ["user", "l", None, "Log in using this user name."],
        ["identity", "i", None],
        ["ciphers", "c", None],
        ["macs", "m", None],
        ["port", "p", None, "Connect to this port.  Server must be on the same port."],
        ["option", "o", None, "Ignored OpenSSH options"],
        ["host-key-algorithms", "", None],
        ["known-hosts", "", None, "File to check for host keys"],
        ["user-authentications", "", None, "Types of user authentications to use."],
        ["logfile", "", None, "File to log to, or - for stdout"],
    ]

    optFlags = [
        ["version", "V", "Display version number only."],
        ["compress", "C", "Enable compression."],
        ["log", "v", "Enable logging (defaults to stderr)"],
        ["nox11", "x", "Disable X11 connection forwarding (default)"],
        ["agent", "A", "Enable authentication agent forwarding"],
        ["noagent", "a", "Disable authentication agent forwarding (default)"],
        ["reconnect", "r", "Reconnect to the server if the connection is lost."],
    ]

    compData = usage.Completions(
        mutuallyExclusive=[("agent", "noagent")],
        optActions={
            "user": usage.CompleteUsernames(),
            "ciphers": usage.CompleteMultiList(
                [v.decode() for v in SSHCiphers.cipherMap.keys()],
                descr="ciphers to choose from",
            ),
            "macs": usage.CompleteMultiList(
                [v.decode() for v in SSHCiphers.macMap.keys()],
                descr="macs to choose from",
            ),
            "host-key-algorithms": usage.CompleteMultiList(
                [v.decode() for v in SSHClientTransport.supportedPublicKeys],
                descr="host key algorithms to choose from",
            ),
            # "user-authentications": usage.CompleteMultiList(?
            # descr='user authentication types' ),
        },
        extraActions=[
            usage.CompleteUserAtHost(),
            usage.Completer(descr="command"),
            usage.Completer(descr="argument", repeat=True),
        ],
    )

    def __init__(self, *args, **kw):
        usage.Options.__init__(self, *args, **kw)
        self.identitys = []
        self.conns = None

    def opt_identity(self, i):
        """Identity for public-key authentication"""
        self.identitys.append(i)

    def opt_ciphers(self, ciphers):
        "Select encryption algorithms"
        ciphers = ciphers.split(",")
        for cipher in ciphers:
            if cipher not in SSHCiphers.cipherMap:
                sys.exit("Unknown cipher type '%s'" % cipher)
        self["ciphers"] = ciphers

    def opt_macs(self, macs):
        "Specify MAC algorithms"
        if isinstance(macs, str):
            macs = macs.encode("utf-8")
        macs = macs.split(b",")
        for mac in macs:
            if mac not in SSHCiphers.macMap:
                sys.exit("Unknown mac type '%r'" % mac)
        self["macs"] = macs

    def opt_host_key_algorithms(self, hkas):
        "Select host key algorithms"
        if isinstance(hkas, str):
            hkas = hkas.encode("utf-8")
        hkas = hkas.split(b",")
        for hka in hkas:
            if hka not in SSHClientTransport.supportedPublicKeys:
                sys.exit("Unknown host key type '%r'" % hka)
        self["host-key-algorithms"] = hkas

    def opt_user_authentications(self, uas):
        "Choose how to authenticate to the remote server"
        if isinstance(uas, str):
            uas = uas.encode("utf-8")
        self["user-authentications"] = uas.split(b",")