doushan2224 2018-08-26 09:49
浏览 393
已采纳

golang使用ssh连接到ssh并打印错误异常

I want to convert python code in golang version, this is my python code:

#!/usr/bin/env python

import argparse
import logging
import paramiko
import socket
import sys


class InvalidUsername(Exception):
    pass


def add_boolean(*args, **kwargs):
    pass


old_service_accept = paramiko.auth_handler.AuthHandler._handler_table[
        paramiko.common.MSG_SERVICE_ACCEPT]

def service_accept(*args, **kwargs):
    paramiko.message.Message.add_boolean = add_boolean
    return old_service_accept(*args, **kwargs)


def userauth_failure(*args, **kwargs):
    raise InvalidUsername()


paramiko.auth_handler.AuthHandler._handler_table.update({
    paramiko.common.MSG_SERVICE_ACCEPT: service_accept,
    paramiko.common.MSG_USERAUTH_FAILURE: userauth_failure
})

#logging.getLogger('paramiko.transport').addHandler(logging.NullHandler())

sock = socket.socket()
sock.connect(("206.189.86.110", 22))

transport = paramiko.transport.Transport(sock)
transport.start_client()

try:
    transport.auth_publickey("root", paramiko.RSAKey.generate(2048))
except InvalidUsername:
    print '[*] Invalid username'
    sys.exit(3)
except paramiko.ssh_exception.AuthenticationException:
    print '[+] Valid username'

this is my curent golang code : https://play.golang.org/p/rzZ7f_if7Wk , I want to create same exception like python code version except InvalidUsername: and paramiko.ssh_exception.AuthenticationException , how I can do this?

  • 写回答

1条回答 默认 最新

  • duanjia1870 2018-08-26 14:41
    关注

    First of all, I feel the approach you're taking is a little odd. Python and Go are two distinct programming languages, with different coding paradigms and totally different ways of handling error/exceptions. Hence, starting with a piece of Python code and converting it to Go might not always be straightforward.

    Since your question is eventually about handling exceptions, this is a simple article on how Go handles errors: https://blog.golang.org/error-handling-and-go (In summary, functions deliberately return errors as values, and anyone who calls the functions checks if an error has been returned and then does whatever it wants e.g. panic, print the error, or return the error upstream, etc.)

    In the Go Playground link you provided, a lot of things can be discussed - the use of ssh package, handling or errors etc. Here is a quick code focusing on the exception handling (and not the ssh package and logic).

    NOTE: This is NOT a demonstartion of how to use the ssh package to authenticate, so please don't use it for such. This is just an example of how I would introduce custom standardized exceptions/errors in the logic.

    import (
        "fmt"
        "golang.org/x/crypto/ssh"
    )
    
    var ErrInvalidUsername error = fmt.Errorf("Invalid Username")
    var ErrAuthenticationFailed error = fmt.Errorf("Authentication Failure")
    var ErrPublicKeyNotParsed error = fmt.Errorf("Could not parse the public key")
    
    func AuthenticateExample(username string, publicKey []byte) error {
        // let's assume there is a function isValidUsername that takes a username and returns bool 
        if !isValidUsername(username) { 
            return ErrInvalidUsername
        }
    
        // do your ssh auth logic here, call ssh package functions which will return an error
        // such as...
        pubKey, err := ssh.ParseKey(publicKey)
        if err != nil {
            return ErrPublicKeyNotParsed 
            // OR you could simple also return the err variable itself by using:
            // return err
        }
    
        // do more logic, and return ErrAuthenticationFailure is needed
        // ... 
    
        return nil // since there is no error if we reach this line
    }
    

    I hope this helps explain Go's exception handling a little. Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog