使用python通过ssh同步文件

#!usr/bin/python
# coding: utf-8
import os
import socks
import socket
import paramiko

os.chdir(os.path.dirname(os.path.abspath(__file__)))

# 没有代理可删掉 import socks import socket 和下边两行代码
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 1080, False, '', '')
socket.socket = socks.socksocket

remoteDir = '服务器路径'
localDir = '本地路径'
hostname = '服务器ip'
port = 22
username = '服务器用户名'
password = '服务器密码'

if __name__ == "__main__":
    scp = paramiko.Transport((hostname, port))
    scp.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(scp)
    files = sftp.listdir(remoteDir)
    for f in files:
        localFile = os.path.join(localDir, f)
        remoteFile = remoteDir + "/" + f
        if not os.path.isfile(localFile):
            sftp.get(remoteFile, localFile)
            print "Download: " + f
        else:
            print "Exists: " + f
    scp.close()

点赞

发表评论

邮箱地址不会被公开。 必填项已用*标注