I can't figure out what's going on, I keep getting this error when I try to establish a tunnel to my VPS to send commands and receive it's output. I've got the VPS SSH keys, tried both "id_rsa" and "id_rsa.pub" but neither worked. What am I doing wrong? Also, if you spot anything else out then let me know!
import paramiko
from paramiko.client import SSHClient
def establish_ssh_tunnel():
global tunnel
# SSH connection details
ssh_host = '***.***.**.***'
ssh_port = 22
ssh_username = '********'
ssh_password = '*****************'
# Local port to bind for tunnel
local_port = 12345
# Create SSH client
client = paramiko.SSHClient()
key = paramiko.RSAKey.from_private_key_file("id_rsa")
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Connect to the remote server
client.connect(ssh_host, ssh_port, ssh_username, ssh_password, pkey=key)
# Open an SSH tunnel
tunnel = client.get_transport().open_channel(
"direct-tcpip",
dest_addr=('localhost', local_port),
src_addr=('localhost', 0)
)
print(f"SSH tunnel established. Listening on port {local_port}")
# Wait for incoming commands on the tunnel
while True:
# Accept a command
command = tunnel.recv(1024).decode().strip()
if command == 'exit':
break
# Process the command (replace with your logic)
response = process_command(command)
# Send the response back through the tunnel
tunnel.send(response.encode())
# Close the SSH tunnel and disconnect from the remote server
if tunnel is not None:
tunnel.close()
client.close()
print("SSH tunnel closed.")
except paramiko.AuthenticationException:
print("Authentication failed. Please check your credentials.")
except paramiko.SSHException as ssh_ex:
print(f"Error connecting to the remote server: {ssh_ex}")
except Exception as ex:
print(f"Error: {ex}")
def process_command(command):
if command == 'hello':
return "Hello, world!"
elif command == 'time':
import datetime
now = datetime.datetime.now()
return str(now)
else:
return "Unknown command"
if __name__ == "__main__":
establish_ssh_tunnel()