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

python 实现多个文件拷贝到ssh 目标机子

2014-02-20 18:49 561 查看
开发需要在远程机子上测试,但是有时候需要本地编辑修改,可以使用scp命令,进行文件拷贝。 一个文件还好,如果文件比较多,如果还再需要拷贝到好几个网络地址上去,就比较麻烦,为了方便就写了个脚本,代码如下:
#! /usr/bin/env python
# coding:utf-8

import os
import getopt
import sys
import commands
import pexpect
import time

def main():
opt,args = getopt.getopt(sys.argv[1:],"")
ip = args[0]

cmd1 = '/usr/bin/scp /Users/qc/Desktop/SourceDir/'
cmd2 = ' root@'
cmd3 = ':/usr/local/DestDir/'

fout = open("log.txt", 'w')
files = ('test_file.txt','testfile2.txt')

ssh_newkey = '''(A-Z|a-z|0-9|:\(\)\'.)* Are you sure you want to continue connecting (yes/no)? '''
need_pwd= 'root@'+ip+"'s password: "
#这里是ssh 主机的密码
pwd = '123456'

for file in files:
cmd =  cmd1+file+cmd2+ip+cmd3+file
print cmd

child = pexpect.spawn(cmd)
child.logfile = fout

i = child.expect([pexpect.TIMEOUT, need_pwd])

if i == 1:

child.sendline(pwd)
print child.before, child.after
else:
print child.before, child.after
child.sendline ('yes')

i = child.expect([pexpect.TIMEOUT, need_pwd])
if i == 1:
child.expect(need_pwd)
child.sendline(pwd)
else:
print 'error:'
print child.before,child.after
break

#等待拷贝完成
time.sleep(5)

fout.close()

#if __name__ == "__main__":
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: