可以连接到本地网络上的套接字,但不能连接到单独的套接字(python套接字)

时间:2020-06-21 07:49:27

标签: python sockets

我一直在尝试制作一个程序,使我可以远程进入计算机。当两台计算机都连接到同一网络时,它可以完美地工作,而且我能够访问一种已经编码的命令行。

我对网络非常缺乏经验,我也不完全确定需要哪种信息。

这是我使用的代码:

服务器:

import sys
import socket

def create_socket():
    try:
        global host
        global port
        global s
        host = ""
        port = 9999
        s = socket.socket()

    except socket.error as msg:
        print("SocketCreationError: " +str(msg))

def bind_socket():
    try:
        global host
        global port
        global s

        print("binding the port " + str(port)+"...")

        s.bind((host,port))
        s.listen(5)

        
    except socket.error as msg:
        print("SocketBindingError: " + str(msg))
        print("retrying...")
        bind_socket()

def socket_accept():
    conn,address = s.accept()
    print("Connection established. \nIP:"+address[0]+"\nPort:"+str(address[1]))
    print(str(conn.recv(1024), "utf-8"), end="")
    send_command(conn)
    conn.close()

#allows user to send command to client computer
def send_command(conn):
    while True:
        try:
            cmd = input(">")
            if cmd == 'exit':
                conn.close()
                s.close()
                sys.exit()
            if len(str.encode(cmd)) > 0:
                conn.send(str.encode(cmd))
                clientResponse = str(conn.recv(1024),"utf-8")
                print(clientResponse, end="")
        except Exception:
            print("Something went wrong...")

def main():
    create_socket()
    bind_socket()
    socket_accept()

main()

客户:

import socket
import os
import subprocess

#connect to socket and send cwd
s = socket.socket()
host = 'myIP'
port = 9999

s.connect((host, port))
s.send(str.encode(os.getcwd()))

#allows form of command line on host pc
while True:
    try:
        data = s.recv(1024)
        outputStr = ""
        
        if data.decode("utf-8") == 'dir':
            dirList = os.listdir(os.getcwd())
            
            for i in dirList:
                print(i)
                outputStr = outputStr + i + "\n"
                
        elif data[:2].decode("utf-8") == 'cd':
            dirTo = data[3:].decode("utf-8")
            print(data[3:].decode("utf-8"))
            os.chdir(os.getcwd() + "\\" + dirTo)
        elif len(data) > 0:
            cmd = subprocess.Popen(data.decode("utf-8"), shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE, stderr=subprocess.PIPE)
            outputByte = cmd.stdout.read() + cmd.stderr.read()
            outputStr = str(outputByte, "utf-8")
            print(outputStr)
            
        cwd = os.getcwd()
        s.send(str.encode(outputStr +"\n"+cwd))

#handle something going wrong and just allows to continue
    except Exception:
        cwd = os.getcwd()
        s.send(str.encode("Something went wrong...\n"+ cwd))

我正在使用ipv4地址。我认为这可能与服务器端的端口转发有关,但我不确定吗?

感谢您提前提出任何答案:)

1 个答案:

答案 0 :(得分:0)

由于端口转发,您无法使用远程网络连接到计算机。如果您不知道这是什么,我建议您看一下有关Wikipedia的文章:https://en.wikipedia.org/wiki/Port_forwarding 有许多种执行端口转发的方法,最简单的方法是UPnP / IGD(查找它),但是如果您只想能够远程访问计算机,则可以使用SSH(安全Shell)连接)来完成此操作(我认为它也可以在远程网络上运行)。如果您使用的是Linux,则应该很容易设置它,只需查看操作方法即可。祝你好运!