Python3 Paramiko SSH Server: Create and Manage Secure Connections
To create an SSH server using Paramiko in Python 3, you can follow the example below: \n\npython\nimport paramiko\n\nclass MySSHServer(paramiko.ServerInterface):\n def check_auth_password(self, username, password):\n if username == "admin" and password == "password":\n return paramiko.AUTH_SUCCESSFUL\n return paramiko.AUTH_FAILED\n \n def check_channel_request(self, kind, chanid):\n if kind == "session":\n return paramiko.OPEN_SUCCEEDED\n return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED\n \n def check_channel_exec_request(self, channel, command):\n # Allow any command to be executed\n return True\n\n# Create an SSH transport\ntransport = paramiko.Transport(("localhost", 22))\n\n# Load the server host key from a file\nhost_key = paramiko.RSAKey(filename="host_key.pem")\ntransport.add_server_key(host_key)\n\n# Start the SSH server\nserver = MySSHServer()\ntransport.start_server(server=server)\n\n# Accept connections and handle requests\nwhile True:\n client = transport.accept()\n channel = client.open_session()\n channel.invoke_shell()\n while True:\n # Handle incoming commands\n command = channel.recv(1024).decode()\n if command.strip() == "exit":\n break\n output = "Command '{}' not recognized." .format(command.strip())\n channel.send(output.encode())\n channel.close()\n\n\nIn this example, the MySSHServer class is a subclass of paramiko.ServerInterface that overrides the necessary methods for authentication and channel requests. In this case, authentication is successful if the username is "admin" and the password is "password". The server allows any session and exec requests, meaning any command can be executed.\n\nThe server uses an SSH transport to listen for incoming connections on localhost port 22. It loads the server host key from a file (e.g., host_key.pem). Then, it starts the SSH server and enters a loop to accept connections and handle requests.\n\nInside the loop, the server accepts a client connection and opens a session channel. It invokes a shell on the channel, allowing the client to execute commands. The server continuously receives commands from the client, handles them, and sends back the output. The loop breaks if the received command is "exit". Finally, the channel is closed.\n\nNote that this is a basic example, and you may need to customize it according to your requirements. Additionally, you may need to handle exceptions and implement proper error handling for production use.
原文地址: https://www.cveoy.top/t/topic/qnl2 著作权归作者所有。请勿转载和采集!