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.
- practically the answer: stackoverflow.com/q/498538/178576 - aleksandr barakin
- It may be more convenient to execute the remote command using fabric . - jfs
|
1 answer
# -*- 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')) # ΠΈ Π·Π°ΠΏΠΈΡΡΡ Π²ΡΠ²ΠΎΠ΄Π° Π² Π»ΠΎΠ³ - oneHUGE TO YOU, human Thank you!) I read your code, I'll try to figure it out. Thanks again! - Alexander Sergeev
- oneprogramcreek.com/python/example/4561/paramiko.SSHClient - vadim vaduxa
|