python 找不到socket_python-‘Port’对象没有属性’socket’

在尝试创建并停止一个自定义端口上的简单SSH服务器时,遇到'Port'对象没有'socket'属性的错误。该错误发生在尝试重启服务器时,由于端口尚未正确释放,导致无法再次监听相同的端口。问题可能源于端口释放和重新启动的逻辑。解决方案可能包括确保在停止服务器后正确关闭和清理端口资源。
摘要由CSDN通过智能技术生成

我正在使用扭曲的python在自定义端口上制作一个简单的SSH服务器.我创建一个Port对象,其端口为port = Reactor.listenTCP(_port,sshfactory),其中_port是保存端口整数的变量.当使用命令port.loseConnection()和port.connectionLost(reason = None)关闭服务器时,我释放了端口.如果我尝试启动服务器,将其停止,然后再次启动,则会出现标题错误“端口”对象没有属性“套接字”

编辑:完整的错误消息:

Unhandled error in Deferred:

Traceback (most recent call last):

File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 1175, in mainLoop

self.runUntilCurrent()

File "C:\Python27\lib\site-packages\twisted\internet\base.py", line 779, in runUntilCurrent

call.func(*call.args, **call.kw)

File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 238, in callback

self._startRunCallbacks(result)

File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 307, in _startRunCallbacks

self._runCallbacks()

--- ---

File "C:\Python27\lib\site-packages\twisted\internet\defer.py", line 323, in _runCallbacks

self.result = callback(self.result, *args, **kw)

File "C:\Python27\lib\site-packages\twisted\internet\task.py", line 736, in

d.addCallback(lambda ignored: callable(*args, **kw))

File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 981, in connectionLost

self._closeSocket()

File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 92, in _closeSocket

skt = self.socket

exceptions.AttributeError: 'Port' object has no attribute 'socket'

Edit2:stopListening代码示例(Python 2.7):

stopListening sample.py

from twisted.cred import portal, checkers, credentials

from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces

from twisted.conch.ssh import factory, userauth, connection, keys, session, common

from twisted.conch.insults import insults

from twisted.application import service, internet

from twisted.internet import reactor, protocol

from zope.interface import implements

import threading

import os

class SSHDemoProtocol(recvline.HistoricRecvLine):

def __init__(self, user):

self.user = user

def connectionMade(self):

recvline.HistoricRecvLine.connectionMade(self)

self.showPrompt()

def showPrompt(self):

self.terminal.write("$")

class SSHDemoRealm:

implements(portal.IRealm)

def requestAvatar(self, avatarId, mind, *interfaces):

if conchinterfaces.IConchUser in interfaces:

return interfaces[0], SSHDemoAvatar(avatarId), lambda: None

else:

raise Exception("No supported interfaces found.")

def getRSAKeys():

if not (os.path.exists('public.key') and os.path.exists('private.key')):

# generate a RSA keypair

print("Generating RSA keypair...")

from Crypto.PublicKey import RSA

KEY_LENGTH = 1024

rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)

publicKeyString = keys.makePublicKeyString(rsaKey)

privateKeyString = keys.makePrivateKeyString(rsaKey)

# save keys for next time

file('public.key', 'w+b').write(publicKeyString)

file('private.key', 'w+b').write(privateKeyString)

print("done.")

else:

publicKeyString = file('public.key').read()

privateKeyString = file('private.key').read()

return publicKeyString, privateKeyString

def launchServer():

_port = 4564

password = 'password'

sshFactory = factory.SSHFactory()

sshFactory.portal = portal.Portal(SSHDemoRealm())

users = {'user': password}

sshFactory.portal.registerChecker(

checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

pubKeyString, privKeyString = getRSAKeys()

sshFactory.publicKeys = {

'ssh-rsa': keys.getPublicKeyString(data=pubKeyString)}

sshFactory.privateKeys = {

'ssh-rsa': keys.getPrivateKeyObject(data=privKeyString)}

global port

port = reactor.listenTCP(_port, sshFactory)

reactor.addSystemEventTrigger('before', 'shutdown', stopServer)

reactor.run(installSignalHandlers=False)

def startServer():

thread = threading.Thread(target=launchServer)

thread.start()

def stopServer():

global port

port.stopListening()

reactor.stop()

reactor.crash()

startServer()

stopServer()

startServer()

追溯:

>>> Exception in thread Thread-2:

Traceback (most recent call last):

File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner

self.run()

File "/usr/lib/python2.7/threading.py", line 505, in run

self.__target(*self.__args, **self.__kwargs)

File "/home/paul/Desktop/Down2Home/stopListening sample.py", line 62, in launchServer

port = reactor.listenTCP(_port, sshFactory)

File "/usr/local/lib/python2.7/dist-packages/Twisted-9.0.0-py2.7-linux-x86_64.egg/twisted/internet/posixbase.py", line 355, in listenTCP

p.startListening()

File "/usr/local/lib/python2.7/dist-packages/Twisted-9.0.0-py2.7-linux-x86_64.egg/twisted/internet/tcp.py", line 855, in startListening

raise CannotListenError, (self.interface, self.port, le)

CannotListenError: Couldn't listen on any:4564: [Errno 98] Address already in use.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值