0

I am trying to get the output from a command using this code

import time

import paramiko

host = "myserver.com"
username = "user"
password = "pass"

ssh = paramiko.SSHClient()
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=username, password=password)

commands = ["sudo su - abc", "mkdir foo"]

channel = ssh.invoke_shell()


time.sleep(1)
channel.recv(9999)
time.sleep(1)

for command in commands:
    channel.send(command + "\n")
    while not channel.recv_ready():
        time.sleep(0.1)
    time.sleep(0.1)
    output = channel.recv(9999)
    print(output.decode("utf-8"))
    time.sleep(0.1)
channel.close()

I am using invoke_shell because I need to run commands using another user in a session, but when I run the commands the output is different from exec_command()

exec_command() show the output from the command, while channel.recv(9999) shows the output from the terminal.

Is there a way to get the output from the command as exec_command() provides? Thank you for the attention.

Antonio Costa
  • 101
  • 1
  • 6
  • Huuuum... How can I send the command as another user without sudo su - user -c? In my case, -c it's not available as well. I need to login as the user and exec the commands. – Antonio Costa Sep 27 '22 at 21:04
  • Oh got it. My problem is that I don't have the password for every user that I will run this automation. I just have a password that I can connect to the server, and this user has root privileges. – Antonio Costa Sep 27 '22 at 21:58
  • "As the last resort option, you can write the command to a standard input of the su, the same way you already write a password (another thing not to do):" Sorry if I am wrong, but to do this I need the password for each user, right? I just have the password for a user that has root privilegies. – Antonio Costa Sep 28 '22 at 06:21
  • I mean, if I type _su_ instead of _sudo_, I need to send the password, right? My problem is when I execute `sudo su - abc` I can't execute anything after that. – Antonio Costa Sep 28 '22 at 13:49
  • I'm not asking you to use `su` directly. Keep using `sudo su`, if that works for you. I was showing you how to run the commands under `su` (and you *are* running commands user `su`, it does not matter that you run `su` via `sudo`). – Martin Prikryl Sep 28 '22 at 14:07
  • Oh got it. Actually, even sudo it's not working for me. – Antonio Costa Sep 28 '22 at 19:07
  • If I type `sudo su - user` and after `command` it works, now, if I do this using paramiko it doesn't – Antonio Costa Sep 30 '22 at 03:49
  • Show us your code. – Martin Prikryl Sep 30 '22 at 05:58

0 Answers0