Python模块之pexpect

最近有需求要配置十几台机器,如果一台一台的去配置,太麻烦了,不是咱的风格,正好用python搞,目前功能还比较简陋而且重叠太多,先凑合着用吧,有时间再优化:

#!/usr/bin/python2.7
#coding:utf-8

import pexpect
import threading

_IPLIST = ['192.168.1.%s' % str(s) for s in range(103, 104)]
_CMDLIST = ['mkdir /home/test/work/test', 'touch /home/test/work/test/test.log', 'echo "test" >> /home/test/work/test/test.log']
_USER = 'root'
_PWD = 'root'

def doSSH(user, pwd, ip, cmdlist):
    ssh = pexpect.spawn('ssh %s@%s' % (user, pwd))
    try:
        r = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=30)
        print r
        if 0 == r:
            ssh.sendline(pwd)
        elif 1 == r:
            ssh.sendline('yes')
            ssh.expect("password:")
            ssh.sendline(pwd)
        for cmd in cmdlist:
            ssh.sendline(cmd)
            result = ssh.read()
            print result
    except pexpect.EOF:
        print "EOF"
    except pexpect.TIMEOUT:
        print "Connected time out"
    finally:
        ssh.close()

def doSCP(user, pwd, ip, source, dest):
    scp = pexpect.spawn('scp %s %s@%s:%s' % (source, user, ip, dest))
    try:
        r = ssh.expect("")
    except pexpect.EOF:
        print "EOF"
    except pexpect.TIMEOUT:
        print "Connected time out"
    finally:
        scp.close()


if __name__ == "__main__":
    for i in _IPLIST:
        threading.Thread(target=doSSH, args=(_USER, _PWD, i, _CMDLIST)).start()
#        doSSH(_USER, _PWD, i, _CMDLIST)


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值