Source code for reemote.operations.sftp.write_file
# Copyright (c) 2025 Kim Jarvis TPF Software Services S.A. kim.jarvis@tpfsystems.com # This software is licensed under the MIT License. See the LICENSE file for details.#importasyncsshfromreemote.commandimportCommand
[docs]classWrite_file:""" A class to encapsulate the functionality of writing builtin in Unix-like operating systems. It allows users to specify text to be written to a builtin. Attributes: path (str): The builtin path where content is to be written. text (str): The builtin content. **Examples:** .. code:: python # Create a builtin from text r = yield Write_file(path='example.txt', text='Hello World!') # Verify the builtin content r = yield Shell("cat example.txt") print(r.cp.stdout) Usage: This class is designed to be used in a generator-based workflow where commands are yielded for execution. """def__init__(self,path:str,text:str):self.path=pathself.text=textdef__repr__(self):returnf"Write_file(path={self.path!r}, text={self.text!r})"@staticmethodasyncdef_write_file_callback(host_info,global_info,command,cp,caller):"""Static callback method for builtin writing"""# Validate host_info (matching Read_file error handling)required_keys=['host','username','password']forkeyinrequired_keys:ifkeynotinhost_infoorhost_info[key]isNone:raiseValueError(f"Missing or invalid value for '{key}' in host_info.")# Validate caller attributes (matching Read_file error handling)ifcaller.pathisNone:raiseValueError("The 'path' attribute of the caller cannot be None.")ifcaller.textisNone:raiseValueError("The 'text' attribute of the caller cannot be None.")try:# Connect to the SSH serverasyncwithasyncssh.connect(**host_info)asconn:print("Connected successfully. Starting SFTP session...")# Start an SFTP sessionasyncwithconn.start_sftp_client()assftp:print(f"Writing content to {caller.path}...")# Define the string content to be writtencontent=caller.text# Open the remote builtin in write mode and write the contentasyncwithsftp.open(caller.path,'w')asremote_file:r=awaitremote_file.write(content)print(f"Successfully wrote builtin {caller.path} on {host_info['host']} r {r}")except(OSError,asyncssh.Error)asexc:print(f'SFTP operation failed on {host_info["host"]}: {str(exc)}')raisedefexecute(self):r=yieldCommand(f"{self}",local=True,callback=self._write_file_callback,caller=self)r.executed=Truer.changed=Truereturnr