2

I'm trying to send an output of a specific command to a txt file,

file = 'output_from_the_server.txt'

def connect(host):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=host, port=port, username=username, password=password, look_for_keys=False, allow_agent=False)
    ssh = client.invoke_shell()
    return ssh

def test(server_host):
    print(server_host)
    IP = server_view(server_host)
    print(IP)
    ssh = connect(IP)
    time.sleep(2)
    ssh.send('clear -x && [command]\n')
    time.sleep(3)
    resp = ssh.recv(655353)
    output = resp.decode('ascii').split(',')
    output = ''.join(output)
    ssh.close()

    with open(file, 'w') as f:
        for i in output:
            f.write(i)
    f.close()

The file include all of the outputs before the command, even i tried to use clear screen.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
nikol
  • 33
  • 3

2 Answers2

1

You are starting a shell, so naturally you get all the output you would get in the shell, including all prompts and banners.

Do not use shell to automate command execution, use the "exec" SSH channel.

stdin, stdout, stderr = client.exec_command(command)
stdout.channel.set_combine_stderr(True)
output = stdout.readlines()

See Paramiko: read from standard output of remotely executed command.


Related question:
Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?


Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

Here's an example of executing a command through a paramiko.

Sending the output to a file should then be easy.

def ssh_command(ip, user, command):
    key = paramiko.RSAKey.from_private_key_file(os.getenv('HOME') + '/.ssh/paramiko')
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(ip, username=user, pkey=key)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        ssh_session.exec_command(command)
        out = []
        r = ssh_session.recv(1024).decode('utf-8')
        while r:
            out.append(r)
            r = ssh_session.recv(1024).decode('utf-8')

        return ''.join(out)
    return ''

res = ssh_command('127.0.0.1', 'user', 'cd / ; ls */ | xargs ls')
for outputin str(res).split('\\n'):
    print(output)

Don't forget to generate a key with ssh-keygen.

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98