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

开发需要在远程机子上测试,但是有时候需要本地编辑修改,可以使用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()


你可能感兴趣的:(python 实现多个文件拷贝到ssh 目标机子)