您的位置:首页 > 编程语言 > Python开发

Python配合SCP实现文件批量下发

2017-03-03 15:29 381 查看
# -*- coding: utf-8 -*-
#!/usr/bin/env python

import pexpect,os    #导入需要用到模块

def ssh_cmd(ip, shell_cmd):
passwd= '1qaz#EDC'
print 'host: %s is connected... ' % ip
child = pexpect.spawn('ssh root@%s' % (ip))
fout = file('log.txt','a')
child.logfile = fout
try:
i = child.expect('password:')
if i == 0:
child.sendline(passwd)
elif i == 1:
child.sendline('yes\n')
child.expect('password: ')
child.sendline(passwd)
print 'host:%s Login ok!' % ip
child.expect('#')
child.sendline(shell_cmd)    #执行传过来的shell命令
child.expect('#')
print 'host:%s Command Execution ok!' % ip
except pexpect.EOF:
print "Command run ok!"
child.close()
except pexpect.TIMEOUT:
print "Connect Timeout..."
child.close()

#前面的ssh_cmd()作用为建立ssh连接

for i in range(165,167):
ipaddr = '192.168.122.%s' % i
ssh_cmd(ipaddr,'mkdir -p /etc/ceph')    #ssh连接上远程主机后,在远程主机创建制定目录

os.environ['ip']=str(ipaddr)    #python变量和shell变量互用
os.system('sshpass -p 1qaz#EDC scp /home/testfile*.conf root@$ip:/etc/ceph')    #文件下发
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python