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

本文介绍了一个用Python编写的脚本,该脚本利用scp命令实现文件的批量远程复制。通过这个脚本,用户可以在多个远程服务器间高效地传输文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值