I am working on a code that: Executes client command during TCP Server.
Server code:
import socket
import paramiko
import threading
# SSH sunucu bilgileri
SSH_HOST = ("localhost")
SSH_PORT = 22
SSH_USERNAME = "skonuvs"
SSH_PRIVATE_KEY_PATH = "/home/skonuvs/rsakeys"
SSH_PASS = "lelele"
# TCP sunucu bilgileri
TCP_HOST = "0.0.0.0"
TCP_PORT = 53953
def ssh_connect(command):
# SSH istemcisi oluştur
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Özel anahtarı yükle
ssh_private_key = paramiko.RSAKey.from_private_key_file(SSH_PRIVATE_KEY_PATH)
# Sunucuya bağlan
client.connect(SSH_HOST, port=SSH_PORT, username=SSH_USERNAME,password=SSH_PASS, pkey=ssh_private_key)
print(f"Connected to {SSH_HOST}")
# Komut çalıştırma
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read() + stderr.read()
client.send(output.encode())
return output
except Exception as e:
print(f"Failed to connect to {SSH_HOST}: {e}")
return str(e).encode() # Hata durumunda dönecek veriyi encode edin
finally:
# Bağlantıyı kapat
client.close()
def handle_client(client_socket):
print("Client handler started")
while True:
try:
# İstemciden veri al
command = client_socket.recv(1024).decode()
if not command:
break
print(f"Executing command: {command}")
output = ssh_connect(command)
client_socket.send(output)
except Exception as e:
print(f"Error handling client: {e}")
break
# Bağlantıları kapat
client_socket.close()
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_HOST, TCP_PORT))
server.listen(5)
print(f"Listening on {TCP_HOST}:{TCP_PORT}")
while True:
client_socket, addr = server.accept()
print(f"Accepted connection from {addr}")
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == "__main__":
start_server()
Client code
import socket
# TCP sunucu bilgileri
TCP_HOST = "127.0.0.1" # Sunucu adresini buraya yazın
TCP_PORT = 53953
def start_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((TCP_HOST, TCP_PORT))
print(f"Connected to TCP server at {TCP_HOST}:{TCP_PORT}")
while True:
command = input("Enter command to execute on SSH server: ")
if command.lower() == "exit":
break
# Komutu sunucuya gönder
client.send(command.encode())
# Sunucudan sonucu al
response = client.recv(1024).decode()
print(f"Response:n{response}")
# Bağlantıyı kapat
client.close()
if __name__ == "__main__":
start_client()
And when I run at the terminal, I get this error:
Listening on 0.0.0.0:53953
Accepted connection from ('127.0.0.1', 42594)
Client handler started
Executing command: ls -la
Failed to connect to localhost: Authentication failed.
Note: Its not about permissions. I have given all permissions to servers, clients, keys.
I tried changing ip and addresses but it didn’t worked either.