Good day! How to write a code to connect to a remote host with paramiko module to be imported? It is necessary to execute the command using a script (for example, ls -al) and writing the output to the log. In this matter I am still green, but I would really like to understand how this code works. The script should be executed as follows: ssh noob@10.0.1.**> ls -al (on the remote host)> write to log.

1 answer 1

# -*- coding: UTF-8 -*- import paramiko class SSH: def __init__(self, **kwargs): self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.kwargs = kwargs def __enter__(self): '''Как Π½Π°ΠΏΠΈΡΠ°Ρ‚ΡŒ ΠΊΠΎΠ΄ для ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ ΠΊ ΡƒΠ΄Π°Π»Π΅Π½Π½ΠΎΠΌΡƒ хосту с ΠΈΠΌΠΏΡ€ΠΎΡ€Ρ‚ΠΈΡ€ΡƒΠ΅ΠΌΡ‹ΠΌ ΠΌΠΎΠ΄ΡƒΠ»Π΅ΠΌ paramiko''' kw = self.kwargs self.client.connect(hostname=kw.get('hostname'), username=kw.get('username'), password=kw.get('password'), port=int(kw.get('port', 22))) return self def __exit__(self, exc_type, exc_val, exc_tb): self.client.close() def exec_cmd(self, cmd): ''' НСобходимо Π²Ρ‹ΠΏΠΎΠ»Π½ΠΈΡ‚ΡŒ ΠΊΠΎΠΌΠ°Π½Π΄Ρƒ с ΠΏΠΎΠΌΠΎΡ‰ΡŒΡŽ скрипта (ΠΊ ΠΏΡ€ΠΈΠΌ. ls -al)''' stdin, stdout, stderr = self.client.exec_command(cmd) data = stdout.read() if stderr: raise stderr return data.decode() if __name__ == '__main__': with SSH(hostname='vs-...', username='lo...', password='l...', port=22) as ssh: # noob@10.0.1.** out = ssh.exec_cmd('ls -l') print(out) print(out, file=open('log.log', 'a')) # ΠΈ записью Π²Ρ‹Π²ΠΎΠ΄Π° Π² Π»ΠΎΠ³