I am trying to implement a (local fake) server with paramiko
that responds to custom commands just like the original for testing purposes. Mainly copying from the supplied demo server, I managed to come up with this custom method to handle exec_requests for the server implemented via paramiko.ServerInterface
:
def check_channel_exec_request(self,channel,command):
print("User wants to execute '%s'" %(command))
comm_main, comm_add = command.decode().split(sep=" ",maxsplit=1)
if comm_main in self.allowed_commands:
chout = channel.makefile("w")
subprocess.Popen(command,stdout=chout)
return True
else:
return False
After the server is running via:
PORT = 50007 # The same port as used by the server
HOST = 'localhost'
host_key = paramiko.RSAKey(filename = <FILEPATH>)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST,PORT))
sock.listen(1)
conn, addr = sock.accept() # Connected!
with conn:
trans = paramiko.Transport(conn)
trans.add_server_key(host_key)
trans.set_subsystem_handler("job",JobHandler)
server = FakeCluster() # Custom class sublassing paramiko.ServerInterface
trans.start_server(server=server)
chan = trans.accept() # Accept authentication from client
while trans.is_active(): # Do not close until inactive
time.sleep(1)
chan.close()
the client would try to execute echo 123
in the following manner:
PORT = 50007 # The same port as used by the server
HOST = 'localhost'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST,PORT))
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, PORT,username=<USERNAME>,password=<PASSWORD>)
ssh.exec_command("echo 123")
Right now, I am getting the error trying to execute the subprocess
that 'ChannelFile' has no attribute 'fileno'
. Furthermore I am wondering how to later execute a python script as a custom command called by exec_command
. (Maybe by calling a batchfile that calls the python script?)