Package: py_secure_shell_automator
PySecureShellAutomator: A Comprehensive SSH Management Library in PythonPySecureShellAutomator is a robust and versatile Python library that simplifies the process of managing remote Unix hosts via SSH. It's built on top of the powerful Paramiko library, but provides a more user-friendly, high-level interface for executing commands and transferring files over SSH.This library is designed with flexibility in mind, catering to a wide range of use cases. Whether you're automating server tasks, deploying applications, managing cloud infrastructure, or developing software that requires remote execution, PySecureShellAutomator is equipped to handle your needs.Key features of PySecureShellAutomator include:Easy Connection Management: PySecureShellAutomator simplifies the process of establishing SSH connections, supporting both password-based and key-based authentication methods. It also provides options for setting connection and authentication timeouts, and automatically adding the host to the known hosts file.Command Execution: PySecureShellAutomator allows you to execute any command on the remote host and retrieve the output and exit code. It provides options for specifying the user that will execute the command, setting a timeout for the command execution, and handling errors.File Operations: With PySecureShellAutomator, you can easily transfer files to and from the remote host using the SFTP protocol. It provides methods for copying files and handling file transfer errors.Exception Handling: PySecureShellAutomator provides custom exceptions for handling specific types of errors, such as command execution errors and file transfer errors. This allows you to easily catch and handle errors in your code.Whether you're developing a deployment script, automating system administration tasks, or building a web application that interacts with remote servers, PySecureShellAutomator provides the tools you need to manage remote systems with ease.We are always open to new pull requests!ContentsKey FeaturesInstallationUsageKey FeaturesPySecureShellAutomator: A Comprehensive SSH Management Library in PythonContentsKey FeaturesInstallationUsageEstablishing a ConnectionPassword-based AuthenticationKey-based AuthenticationFile OperationsCopy a File to the Remote HostCopy a File from the Remote HostGet Content of a FileCreate a DirectoryGet Scructure of a DirectoryRemove a FileRemove DirectoryProcesses OperationsGet the status of a single processGet All Running ProcessesKill a ProcessUser OperationsCreate a UserDelete a UserSystem Information RetrievalCPU UsageMemory UsageDisk UsageKernel VersionOS VersionExecuting Commands withrun_cmdInstallationYou can install PySecureShellAutomator with pip:pipinstallpy_secure_shell_automatorUsagePySecureShellAutomator is designed to be easy to use. Here's an example of how to connect to a remote host and execute a command:frompy_secure_shell_automatorimportPySecureShellAutomator# Create a PySecureShellAutomator instancessh=PySecureShellAutomator(host='hostname',username='username',password='password')# Use the PySecureShellAutomator instance to perform operationsprocesses=ssh.get_all_running_processes()forprocessinprocesses:print(f"User:{process.user}, PID:{process.pid}, CPU:{process.cpu}, MEM:{process.mem}, Command:{process.command}")>>>User:root,PID:1,CPU:0.1,MEM:1.4,Command:/sbin/initUser:daemon,PID:2,CPU:0.0,MEM:0.1,Command:/usr/sbin/atd-fUser:root,PID:3,CPU:0.2,MEM:0.8,Command:/usr/sbin/cron-fUser:root,PID:4,CPU:0.5,MEM:2.6,Command:/usr/sbin/rsyslogd-nUser:syslog,PID:5,CPU:0.0,MEM:0.3,Command:/usr/sbin/rsyslogd-nUser:root,PID:10,CPU:0.3,MEM:1.4,Command:/sbin/dhclient-1-v-pf/run/dhclient.eth0.pid-lf/var/lib/dhcp/dhclient.eth0.leaseseth0User:root,PID:11,CPU:0.0,MEM:0.1,Command:/sbin/agetty--nocleartty1linuxUser:root,PID:12,CPU:0.0,MEM:0.1,Command:/sbin/agetty--keep-baud115200384009600ttyS0vt220User:root,PID:13,CPU:0.4,MEM:2.2,Command:/usr/lib/postfix/sbin/master-wUser:www-data,PID:14,CPU:2.0,MEM:4.0,Command:/usr/sbin/apache2-kstartEstablishing a ConnectionPySecureShellAutomator allows you to establish an SSH connection to a remote Linux host using the paramiko library. You can customize the connection using several attributes:host: The hostname or IP address of the remote host.username: The username to use for the SSH connection.password: The password to use for the SSH connection. This is required for password-based authentication.port: The port to use for the SSH connection. The default is 22.pkey: The path to the private key file to use for the SSH connection. This is required for key-based authentication.timeout: The maximum amount of time (in seconds) to wait for the connection to be established. Default is 10 seconds.auth_timeout: The maximum amount of time (in seconds) to wait for authentication to complete. Default is 10 seconds.auto_add_policy: If set to True, the host's key will be automatically added to the known hosts file. This is useful if you're connecting to the host for the first time.sftp: If set to True, the SFTP protocol will be used for the connection. This is useful if you need to transfer files to/from the host.Here's how you can establish a connection using password-based authentication and key-based authentication:Password-based Authenticationpass_ssh=PySecureShellAutomator(host='hostname',username='username',password='password')Key-based Authenticationkey_ssh=PySecureShellAutomator(host='hostname',username='username',pkey='path_to_key')Remember to replace 'hostname', 'username', 'password', and 'path_to_key' with your actual host details. Also, ensure that the user has the necessary permissions to establish the SSH connection.File OperationsPySecureShellAutomator provides methods for performing various file operations on the remote host.Observation: TO usesftpoperations, setsftp=Truewhen creating the PySecureShellAutomator instance.Methods that usesftp:copy_file_to_remotecopy_file_from_remoteHere is an example of how to create a PySecureShellAutomator instance withsftpoperations:# Create an instance of SSHFileOperationsssh_file_ops=PySecureShellAutomator(host='hostname',username='username',password='password',sftp=True)The other methods you are free to use withoutsftpset toTrue.
In the following examples, we will use thessh_file_opsinstance to perform file operations, for convenience, but again, you can use any instance of PySecureShellAutomator.Copy a File to the Remote Hostssh_file_ops.copy_file_to_remote('local_path','remote_path')Copy a File from the Remote Hostssh_file_ops.copy_file_from_remote('local_path','remote_path')Get Content of a Filessh_file_ops.get_file_content('remote_path')Create a Directoryssh_file_ops.create_directory('remote_path')Get Scructure of a Directorystructure=ssh_file_ops.get_directory_structure('path')fordirectoryinstructure:print(f"Directory:{directory.dir}")print("Files:")forfileindirectory.files:print(file)Remove a Filessh.remove_file('remote_file_path')Remove Directoryssh.remove_directory('remote_path',recursive=False)# recursive=True to remove recursively, default is FalseProcesses OperationsPySecureShellAutomator provides methods for performing various processes operations on the remote host. Here are some examples of how to use these methods:Get the status of a single processprocesses=ssh.get_single_process_status('process_name')forprocessinprocesses:print(f"User:{process.user}, PID:{process.pid}, CPU:{process.cpu}, MEM:{process.mem}, Command:{process.command}")Get All Running Processesprocesses=ssh.get_all_running_processes()forprocessinprocesses:print(f"User:{process.user}, PID:{process.pid}, CPU:{process.cpu}, MEM:{process.mem}, Command:{process.command}")Kill a Processssh.kill_process('process_name',run_as_root=False)# If necessary, set run_as_root=True to run as root, default is FalseUser OperationsManage user accounts on the remote host, including creating, modifying, and deleting users.Create a Userssh.create_user('username','password',run_as_root=True)# By default, the command is executed as root. If necessary, set run_as_root=False to run as a non-root user.Delete a Userssh.delete_user('username',run_as_root=True)# By default, the command is executed as root. If necessary, set run_as_root=False to run as a non-root user.System Information RetrievalRetrieve comprehensive system information from the remote host, CPU usage, memory usage, and disk usage.Observation: The following methods are not executed as root by default. If necessary, set run_as_root=True to run as root.CPU Usagecpu_usage=ssh.get_cpu_usage()print(f"CPU Usage:{cpu_usage}")Memory Usagemem_usage=ssh.get_memory_usage()print(f"Memory Usage:{mem_usage}")Disk Usagedisk_usage=ssh.get_disk_usage()print(f"Disk Usage:{disk_usage}")Kernel Versionkernel_version=ssh.get_kernel_version()print(f"Kernel version:{kernel_version}")OS Versionos_version=ssh.get_os_version()print(f"OS:{ssh.os_version}")Executing Commands withrun_cmdTherun_cmdmethod is a powerful tool in PySecureShellAutomator that allows you to execute any command on the remote host. This method provides a high level of flexibility and control, with several parameters to customize the command execution:cmd: This is the command you want to execute on the remote host. It can be any command that the remote system recognizes.user: This parameter allows you to specify the user that will execute the command. If not provided, the command will be executed with the same user that was used to establish the SSH connection.raise_exception: If set to True, the method will raise an exception if the command's exit code is not 0, i.e., if the command fails. This is useful if you want to ensure that the command was executed successfully.custom_exception: This parameter allows you to specify a custom exception that will be raised if the command fails andraise_exceptionis set to True. This can be useful for handling specific types of errors.err_message: This is the error message that will be used if an exception is raised. If not provided, the output of the command will be used as the error message.cmd_timeout: This parameter allows you to specify a timeout for the command execution. If the command does not complete within this time, it will be terminated. Default is 10 seconds.Therun_cmdmethod returns aCmdResponseobject, which contains the output of the command and its exit code. You can use this object to check the result of the command and handle it in your code.Here's an example of how to use therun_cmdmethod:frompy_secure_shell_automatorimportPySecureShellAutomator# Create a PySecureShellAutomator instancessh=PySecureShellAutomator(host='hostname',username='username',password='password')# Create a custom commandcommand='uptime'# Execute the custom commandoutput=ssh.run_cmd(command)# Print the outputprint(output.out)# 16:38:59 up  1:02,  1 user,  load average: 0.00, 0.00, 0.00# Print exit codeprint(output.ext_code)# 0# Check if the command was successfulprint(output.is_successful)# True