Teach you to use Python batch update server files

 

 

 

Bought a Linux server, Centos system, installed a pagoda built 10 websites, such as sometimes have to add a little code on a file, we must turn to 10 document changes, although pagoda is a visual page, does not require use command, but also trouble, although there git hook method, but the operation is also troublesome, the new directory, then had to do this once, so the initiation of an idea in Python batch update files on the server
Note: many people learn Python process You will encounter a variety of problems to worry about, no one to help answering easy to give up. For this reason small series built a Python full-stack free Q & A skirt: under seven Yiyi nine plays from Pakistan and five (digital homonym) conversion can be found, but not the older drivers have problems to solve, there is also the latest Python Tutorial Project You can get together with each other ,, supervise progress together!


Preface

Internet search around and found there is a Python library called paramikocan be specifically used to do this thing, and installation of specific information on the Internet to search it, I directly on the code, less than 100 lines, in fact, can also streamline it, behind Besides, to achieve the first function again,Show Code

Code

import paramiko
import os

# 连接信息
host = 'xxx.65.9.191'
port = 22
username = 'root'
password = 'root'

# 忽略的目录
skipArry = ['kai.xxxx.com','demo.xxxx.com']

fullpathArry = []
currentIndex = ''


# 判断文件是否存在
def judgeFileExist():
    global currentIndex;
    currentIndex = os.getcwd() + '/Index.php'
    if os.path.isfile(currentIndex) == False:
        print('Index文件不存在')
        exit()
    print('文件检测成功,准备连接服务器...')



def creatConnect():
    try:
        print('开始连接服务器...')
        s = paramiko.Transport((host, port))
        s.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(s)
        print('连接:' + host + '成功')
        return sftp,s
    except Exception as e:
        print('连接服务器失败:' + str(e))



#

# 获取目录保存为数组
def getDirectory(sftp):
    print('开始获取目录...')
    sftp.chdir('/www/wwwroot')
    pathlist = sftp.listdir(path='.')
    for path in pathlist:
        fullpath = '/www/wwwroot/' + path + '/application/index/controller'
        if path in skipArry:
           continue
        fullpathArry.append(fullpath)
    print('目录获取完毕')

# 上传Index文件
def uploadIndex(sftp):
    for fullpathitem in fullpathArry:
            remoteIndex = fullpathitem + '/Index.php'
            print('开始上传:' + remoteIndex)
            try:
                sftp.put(currentIndex, remoteIndex)
                try:
                    sftp.file(remoteIndex)
                    sftp.chmod(remoteIndex, int("775", 8))
                    print('修改' + remoteIndex + '权限为755')
                    print(fullpathitem + '上传成功')
                except:
                    print(fullpathitem + '上传失败')
                    continue
            except Exception as e:
                print('错误信息:' + str(e))
                continue
     



if __name__ == "__main__":
    judgeFileExist()
    sftp,s = creatConnect()
    getDirectory(sftp)
    uploadIndex(sftp)
    s.close()

Code Show is over, start a detailed explanation wave

This detection method is there under my current directory Index.phpthe file, if not, then it does not exit for the next step, there is a small pit, is your Index.phpfile name, you write lowercase index.php, but also to True, here is to where noted, is to modify currentIndexthe value must be added in front of global, or otherwise be empty

def judgeFileExist():
    global currentIndex;
    currentIndex = os.getcwd() + '/Index.php'
    if os.path.isfile(currentIndex) == False:
        print('Index文件不存在')
        exit()
    print('文件检测成功,准备连接服务器...')

This is the connection to the server and create SFTP, used Tryto capture exception error

def creatConnect():
    try:
        print('开始连接服务器...')
        s = paramiko.Transport((host, port))
        s.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(s)
        print('连接:' + host + '成功')
        return sftp,s
    except Exception as e:
        print('连接服务器失败:' + str(e))

Here is the implementation of the operation command, the sftp objects to manipulate, sftp.chdiris a switch for the directory, the equivalent of shellthe command cd /www/wwwroot
sftp.listdir(path='.')is to return the current file directory folder, and is returned as an array, which is then assembled into the complete path and then saved local backup array, here is if inused to skip some directory sites, such as xxx.demo.com I do not want to update this directory, and wrote in SkipArry beginning of years, used to skip

def getDirectory(sftp):
    print('开始获取目录...')
    sftp.chdir('/www/wwwroot')
    pathlist = sftp.listdir(path='.')
    for path in pathlist:
        fullpath = '/www/wwwroot/' + path + '/application/index/controller'
        if path in skipArry:
           continue
        fullpathArry.append(fullpath)
    print('目录获取完毕')

Here is the key part of the upload, first we need to modify traverse the folder directory, stitching on the need to modify the file later Index.phpdocumented path to the remote server, and then use the sftp.putfunction to upload our files, the first parameter is a local file path, and the second parameter is the path on the remote server, used after successful upload sftp.fileto verify that the file exists, in fact, where I made a backup process (the first time being a little bug commented out), the first original Index.phprenamed to BackIndex.phpupload new Index.php, this function only with a judge, or I write nothing, because the upload did not succeed certainly there will be a Index.phpfile using the upload after a good sftp.chmodway to change the file permissions to 755, there is a pit you write directly on the second parameter 755, you will find the resulting file permissions to 363, after several tests found that the second parameter to be passed in octal 755, that is 493, 755 is generated by the authority, feeling a little pit father.

def uploadIndex(sftp):
    for fullpathitem in fullpathArry:
            remoteIndex = fullpathitem + '/Index.php'
            print('开始上传:' + remoteIndex)
            try:
                sftp.put(currentIndex, remoteIndex)
                try:
                    sftp.file(remoteIndex)
                    sftp.chmod(remoteIndex, int("775", 8))
                    print('修改' + remoteIndex + '权限为755')
                    print(fullpathitem + '上传成功')
                except:
                    print(fullpathitem + '上传失败')
                    continue
            except Exception as e:
                print('错误信息:' + str(e))
                continue

Then walk in the main, we will be able to file in the corresponding directory on the server to replace all my local paper, not much code, but the effect so that ah
Note: Many people learn Python process will encounter all kinds of trouble issue, there is no one to help answering easy to give up. For this reason small series built a Python full-stack free Q & A skirt: under seven Yiyi nine plays from Pakistan and five (digital homonym) conversion can be found, but not the older drivers have problems to solve, there is also the latest Python Tutorial Project You can get together with each other ,, supervise progress together!
Text and images in this article from the network with their own ideas, only to learn, exchange, not for any commercial purposes, belongs to original author, if any questions, please contact us for treatment.

Published 30 original articles · won praise 6 · views 1245

Guess you like

Origin blog.csdn.net/QQ2352108083/article/details/104553473