Python implements SSH batch login and executes commands

From , 5 Years ago, written in Python, viewed 139 times.
URL https://pastebin.vip/view/f885a14e
  1. #!/usr/bin/env python
  2.  
  3. # -*- coding: utf-8 -*-
  4.  
  5.  
  6.  
  7. import pexpect
  8.  
  9.  
  10.  
  11. def ssh_cmd(ip, passwd, cmd):
  12.  
  13.     ret = -1
  14.  
  15.     ssh = pexpect.spawn('ssh root@%s "%s"' % (ip, cmd))
  16.  
  17.     try:
  18.  
  19.         i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
  20.  
  21.         if i == 0 :
  22.  
  23.             ssh.sendline(passwd)
  24.  
  25.         elif i == 1:
  26.  
  27.             ssh.sendline('yes\n')
  28.  
  29.             ssh.expect('password: ')
  30.  
  31.             ssh.sendline(passwd)
  32.  
  33.         ssh.sendline(cmd)
  34.  
  35.         r = ssh.read()
  36.  
  37.         print r
  38.  
  39.         ret = 0
  40.  
  41.     except pexpect.EOF:
  42.  
  43.         print "EOF"
  44.  
  45.         ssh.close()
  46.  
  47.         ret = -1
  48.  
  49.     except pexpect.TIMEOUT:
  50.  
  51.         print "TIMEOUT"
  52.  
  53.         ssh.close()
  54.  
  55.         ret = -2
  56.     return ret
  57.  
  58.  
  59. #//python/5632

Reply to "Python implements SSH batch login and executes commands"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website