python pexpect多机远程管理范例

Standard
#!/usr/bin/python
 
import pexpect
import sys
import time
import os
 
def ssh_cmd(ip, user, pwd, cmds):
  try:
    foo = pexpect.spawn('ssh %s@%s' % (user,ip))
    index = foo.expect(['Password:', 'yes/no'])
 
    if index == 0:
      foo.sendline(pwd)
    elif index == 1:
      foo.sendline('yes')
 
    foo.expect('~ #')
 
    for cmd in cmds.split(","):
      foo.sendline(cmd)
 
  except pexpect.EOF:
    foo.close()
  else:
    foo.close
  return ip
 
file = open('serverlist.txt')
try:
  hosts = file.read()
finally:
  file.close()
 
  for host in hosts.split("\n"):
    if host:
      ip,user,pwd,cmds = host.split(":")
      print ssh_cmd(ip,user,pwd,cmds)
172.28.201.101:yemaosheng:com:echo '1' >> /root/1,echo '11' >> /root/2
172.28.201.102:yemaosheng:com:echo '2' >> /root/2
172.28.201.103:yemaosheng:com:echo '3' >> /root/3

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.