I am trying to execute the following code to execute a linux command
from dataclasses import dataclass
from typing import Type
import paramiko
class CmdError(Exception):
...
@dataclass
class CmdOutput:
ext_code: int
out: str
class SSH:
def __init__(self, hostname, username, password) -> None:
self.username = username
self.password = password
self.hostname = hostname
self.ssh = paramiko.SSHClient()
self.ssh.load_system_host_keys()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self.ssh.connect(hostname=hostname, username=username, password=password)
except Exception as e:
raise e
def exec_cmd(
self,
cmd: str = "",
CustomException: Type[Exception] = CmdError,
raise_exception: bool = True,
) -> CmdOutput:
_, stdout, stderr = self.ssh.exec_command(cmd, get_pty=True)
ext_code = stderr.channel.recv_exit_status()
out = stdout.read().decode("utf-8")
err = ""
if ext_code != 0:
err = stderr.read().decode("utf-8")
if raise_exception:
# Sometimes err is empty, so we need to use out instead
if err != "":
raise CustomException(err)
raise CustomException(out)
return CmdOutput(ext_code=ext_code, out=out)
if __name__ == "__main__":
hostname = "hostname"
username = "username"
password = "password"
ssh = SSH(hostname, username, password)
cmd = """sudo su - user -Hic direct <<< 'command' """
print(ssh.exec_cmd(cmd))
The command sudo su - user -Hic direct <<< 'command'
when executed directly in the machine works perfectly, but when executed using paramiko I receive the error
sh: 0403-057 Syntax error at line 1 : `<' is not expected.
What can I do to execute this command in Paramiko as well? Thank you for the attention.