Using Python to update server files in batch

I bought a Linux server, Centos system, installed a pagoda, and built 10 websites. For example, sometimes if I want to add some code to a file, I need to change 10 files in turn. Although the pagoda is a visual page operation, it doesn't need to use commands, but it's also troublesome. Although there's still a hook method of git, But the operation is also troublesome. If you want to create a new directory, you have to operate it once, so an idea came into being to use Python to batch update files on the server

Note: many people will encounter various problems in the process of learning python. It's easy to give up without help. For this reason, the editor has built a python full stack free Q & A exchange. Skirt: seven clothes, nine lifts, and five (Digital homophony) can be found under conversion. The problems that he doesn't understand are solved by the old driver, and the latest Python tutorial project can be taken, so we can supervise each other and make progress together!

Preface

After a round of searching on the Internet, I found that Python has a library called paramiko that can be used for this purpose. For specific information and installation, I will search on the Internet, and I will directly enter the code, less than 100 lines. In fact, it can be simplified. Later, I will realize the function first, Show Code

Code

import paramiko
import os

# Connection information
host = 'xxx.65.9.191'
port = 22
username = 'root'
password = 'root'

# Directories ignored
skipArry = ['kai.xxxx.com','demo.xxxx.com']

fullpathArry = []
currentIndex = ''


# Judge whether the file exists
def judgeFileExist():
    global currentIndex;
    currentIndex = os.getcwd() + '/Index.php'
    if os.path.isfile(currentIndex) == False:
        print('Index file does not exist')
        exit()
    print('File detection successful,Prepare to connect to the server...')



def creatConnect():
    try:
        print('Start connecting to server...')
        s = paramiko.Transport((host, port))
        s.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(s)
        print('Connect:' + host + 'Success')
        return sftp,s
    except Exception as e:
        print('Failed to connect to server:' + str(e))



#

# Get directory save as array
def getDirectory(sftp):
    print('Start getting directory...')
    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('Directory acquisition completed')

# Upload Index file
def uploadIndex(sftp):
    for fullpathitem in fullpathArry:
            remoteIndex = fullpathitem + '/Index.php'
            print('Start uploading:' + remoteIndex)
            try:
                sftp.put(currentIndex, remoteIndex)
                try:
                    sftp.file(remoteIndex)
                    sftp.chmod(remoteIndex, int("775", 8))
                    print('modify' + remoteIndex + 'The permissions are 755.')
                    print(fullpathitem + 'Upload success')
                except:
                    print(fullpathitem + 'Upload failure')
                    continue
            except Exception as e:
                print('error message:' + str(e))
                continue
     



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

After the code Show, start to explain in detail

This method is to check whether there is an index.php file in my current directory. If there is no file, I will directly exit without going to the next step. Here is a small pit, that is, the file name of your index.php. You can write the index.php in lowercase, which can also be True. Here is a thing to be noted, that is, to modify the value of currentIndex, you must add global in front, otherwise it will still be empty

def judgeFileExist():
    global currentIndex;
    currentIndex = os.getcwd() + '/Index.php'
    if os.path.isfile(currentIndex) == False:
        print('Index file does not exist')
        exit()
    print('File detection successful,Prepare to connect to the server...')

This is to connect to the server and create SFTP, using Try to catch abnormal errors

def creatConnect():
    try:
        print('Start connecting to server...')
        s = paramiko.Transport((host, port))
        s.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(s)
        print('Connect:' + host + 'Success')
        return sftp,s
    except Exception as e:
        print('Failed to connect to server:' + str(e))

Here is the execution of the operation command. Use the sftp object to operate. sftp.chdir is the cd /www/wwwroot used to switch directories, which is equivalent to the shell command
sftp.listdir(path = '.') is to return the folder under the current directory in the form of an array, and then splice it into a full path and save it in the local array for backup. Here is an if in to skip some website directories, such as xxx.demo.com, which I don't want to update, and write it in the SkipArry at the beginning to skip

def getDirectory(sftp):
    print('Start getting directory...')
    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('Directory acquisition completed')

Here is the key upload part. First, traverse the folder directory that we need to modify, then splice the file Index.php that needs to be modified to form the file path of the remote server, and then use the sftp.put function to upload our file. The first parameter is the path of the local file, and the second parameter is the path on the remote server, After the upload is successful, use sftp.file to verify the existence of the file. In fact, I made a backup here (a little bug will be commented out for the time being). First, change the original Index.php to BackIndex.php and upload the new Index.php. This judgment function is useful, but it's useless for me to write like this, There must be an Index.php file if the upload is not successful. After the upload, use the sftp.chmod method to change the permissions of the file to 755. Here is a pit. If you write 755 in the second parameter directly, you will find that the permissions of the generated file are 363. After many experiments, the second parameter needs to be transferred to 755 in octal, that is 493, and the generated permissions are 755, It's a bit of a pit dad.

def uploadIndex(sftp):
    for fullpathitem in fullpathArry:
            remoteIndex = fullpathitem + '/Index.php'
            print('Start uploading:' + remoteIndex)
            try:
                sftp.put(currentIndex, remoteIndex)
                try:
                    sftp.file(remoteIndex)
                    sftp.chmod(remoteIndex, int("775", 8))
                    print('modify' + remoteIndex + 'The permissions are 755.')
                    print(fullpathitem + 'Upload success')
                except:
                    print(fullpathitem + 'Upload failure')
                    continue
            except Exception as e:
                print('error message:' + str(e))
                continue

Then execute in sequence in main, you can replace all the files in the corresponding directory on the server with my local files. There is not much code, but the effect is good

Note: many people will encounter various problems in the process of learning python. It's easy to give up without help. For this reason, the editor has built a python full stack free Q & A exchange. Skirt: seven clothes, nine lifts, and five (Digital homophony) can be found under conversion. The problems that he doesn't understand are solved by the old driver, and the latest Python tutorial project can be taken, so we can supervise each other and make progress together!
The text and pictures of this article come from the Internet and my own ideas. They are only for learning and communication. They have no commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling.

Tags: Python sftp PHP Linux

Posted on Fri, 28 Feb 2020 03:02:06 -0500 by PHPdev