Как подключить клиента к серверу через Интернет без использования SSHPython

Программы на Python
Ответить
Anonymous
 Как подключить клиента к серверу через Интернет без использования SSH

Сообщение Anonymous »

Я пытаюсь подключить клиент, работающий на одном компьютере, к серверу, работающему на другом компьютере, через Интернет, но, похоже, это не работает. Я назову машину, на которой (всегда) работает сервер, «удаленной машиной», а машину, на которой (иногда) работает клиент, — «локальной машиной». Обе машины подключены к одной и той же беспроводной локальной сети.
Я могу использовать SSH с локального компьютера на удаленный, используя как «локальный» IP-адрес удаленного компьютера (192.168.x. y), а также с помощью «внешнего» IP-адреса моего маршрутизатора (98.xx.yy. zz) для переадресации портов (настроенного на маршрутизаторе).
Когда Я подключаюсь по SSH к удаленно (любыми средствами) я могу успешно подключить клиент к серверу, потому что, конечно, клиент и сервер работают на одной машине.
Когда я запускаю клиент на локальном компьютере машина, это работает, если я скажу клиенту использовать «локальный» IP-адрес удаленной машины. Однако, когда я запускаю клиент на локальном компьютере, он НЕ работает, если я говорю клиенту использовать «внешний» IP-адрес удаленного компьютера.
Для ясности, как вы посмотрите на код ниже, вот соответствующие IP-адреса (скрыты):
localhost - remote machine (127.0.0.1),
192.168.x.y - remote machine local wlan,
192.168.g.h - local machine local wlan,
98.xx.yy.zz - router public IP

Вот методы SSH, которые работают:
ssh pi@98.xx.yy.zz -p 2222
ssh pi@192.168.x.y

У клиента есть четыре варианта подключения к серверу. Я протестировал все четыре варианта подключения как для SSH-подключения к удаленному компьютеру, так и для запуска клиента непосредственно на локальном компьютере (всего 8 тестов). Результаты теста представлены ниже.
Заранее благодарим за помощь.
# Relavent client code. #####################################
clientSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connectType=input('local, 192, 98-5000, 98-2222 (1,2,3,4)->')
if connectType == '1':
clientSocket.connect(('localhost', 5000)) #same machine
if connectType == '2':
clientSocket.connect(('192.168.x.y',5000)) #same lan
if connectType == '3':
clientSocket.connect(('98.xx.yy.zz',5000)) #internet 5000
if connectType == '4':
clientSocket.connect(('98.xx.yy.zz',2222)) #internet 2222
#############################################################

# Relavent server code. #####################################
host = '0.0.0.0'
port = 5000
serverSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind((host, port))
serverSocket.listen(5)
print('Server listening on: {} {}'.format(host, port))
while True:
clientSocket, clientAddress = serverSocket.accept()
# Create a new thread to handle the client
print('Starting a new client handler thread.')
cThrd = threading.Thread(target=handleClient,
args=( clientSocket,
clientAddress),
name = 'handleClient-{}'.\
format(clientAddress) )
cThrd.start()
#############################################################

# Relavent handleClient Code. ###############################
print('Accepted connection from: {}'.format(clientAddress))
#############################################################


##SSH CLIENT Screen Grab. Client running on REMOTE MACHINE. ######
pi@raspberrypi:~/python $ python3 client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 1 # use connection type 1.
Choice (m=menu, q=quit) -> gv # send cmd to server.
Version: 2.12 # server responded!
Choice (m=menu, q=quit) -> close
Closing connection
###
pi@raspberrypi:~/python $ python3 client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 2 # use connection type 2.
Choice (m=menu, q=quit) -> gv # send cmd to server.
Version: 2.12 # server responded!
Choice (m=menu, q=quit) -> close
Closing connection
###
pi@raspberrypi:~/python $ python3 client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 3 # use connection type 3.
Traceback (most recent call last): # fail! I understand why.
File "client.py", line 78, in
clientSocket.connect(( '98.xx.yy.zz', 5000 ))
ConnectionRefusedError: [Errno 111] Connection refused
###
pi@raspberrypi:~/python $ python3 client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 4 # use connection type 4.
Choice (m=menu, q=quit) -> gv # send cmd to server.

SSH-2.0-OpenSSH_7.9p1 Raspbian-10 # connected to remote machine
# but not to server running on it.
# That's ok, not worried about
# this case.
Choice (m=menu, q=quit) -> close
pi@raspberrypi:~/python/sprinkler2 $
######################################################

##SSH SERVER Screen Grab. Client running on REMOTE MACHINE ####
pi@raspberrypi:~/python $ python3 server.py
Server listening on: 0.0.0.0 5000

Starting a new client handler thread.
Accepted connection from: ('127.0.0.1',58770) # -> 1
Received from: ('127.0.0.1', 58770) gv
Received from: ('127.0.0.1', 58770) close
Closing: ('127.0.0.1', 58770)

Starting a new client handler thread.
Accepted connection from: ('192.168.x.y',32974)# -> 2
Received from: ('192.168.x.y', 32974) gv
Received from: ('192.168.x.y', 32974) close
Closing: ('192.168.x.y', 32974)

# -> 3

# -> 4
######################################################
##Local Client Screen Grab. Client running on LOCAL Machine ###
PS C:> python .\client.py
local, 192,98-5,98-2 (1,2,3,4) -> 1 # use connection type 1.
Traceback (most recent call last): # Didn't work, I understand why.
File "client.py", line 74, in
clientSocket.connect(( 'localhost', 5000 ))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ConnectionRefusedError: [WinError 10061] No connection
could be made because the target machine refused it
###
PS C:> python .\client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 2 # use connection type 2.
Choice (m=menu, q=quit) -> gv # send cmd to server.
Version: 2.12 # server responded!
Choice (m=menu, q=quit) -> close # Running client on LOCAL
Closing connection # machine WORKS when connected
### # via local (192) IP address.
PS C:> python .\client.py
local, 192, 98-5, 98-2 (1,2,3,4) -> 3 # use connection type 3.
Traceback (most recent call last): # Nope. Figured because I'm
File "client.py", line 78, in # not using the port
# forwarding address.
clientSocket.connect(( '98.xx.yy.zz', 5000 ))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ConnectionRefusedError: [WinError 10061] No connection
could be made because the target machine refused it
###
PS C:> python .\client.py # THIS IS THE SCNERIO I THINK SHOULD WORK.
local,192, 98-5, 98-2 (1,2,3,4)->4 # use connection type 4.
Choice (m=menu, q=quit) -> m # send cmd, get a weird response.
SSH-2.0-OpenSSH_7.9p1 Raspbian-10 # connected to remote machine
# but not to server running on
# it even though I used the port
# forwarding address.
Choice (m=menu, q=quit) -> close
PS C:>
######################################################

##Server Screen Grab. Client running on LOCAL Machine ###########
pi@raspberrypi:~/python $ python3 server.py
Server listening on: 0.0.0.0 5000
# -> 1
Starting a new client handler thread. # -> 2
Accepted connection from:('192.168.g.h',58098)
Received from: ('192.168.g.h', 58098) gv
Received from: ('192.168.g.h', 58098) close
Closing: ('192.168.g.h', 58098)
# -> 3
# -> 4
######################################################



Подробнее здесь: https://stackoverflow.com/questions/792 ... -using-ssh
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»