How to batch update server files with Python

  • 2020-11-30 08:27:48
  • OfStack

preface

Bought a Linux servers, Centos system, installed a pagoda built 10 sites, sometimes to add some code in a file, for example, will, in turn, to 10 files changes, although the pagoda is visual page operation, do not need to use command, but also trouble, although there are git hook method, but also trouble operation, a new directory also have to operate, so had a idea, use Python to batch update the file on the server

The preface

I searched 1 circle on the Internet and found that Python has a library called paramiko, which can be used specifically to do this. The specific information and installation can be searched on the Internet. I directly put the code on, less than 100 lines, in fact, it can be simplified

code


import paramiko
import os

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

#  Ignored directory 
skipArry = ['kai.xxxx.com','demo.xxxx.com']

fullpathArry = []
currentIndex = ''


#  Determine if 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 server ...')



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



#

#  Gets the directory saved as an array 
def getDirectory(sftp):
 print(' Start getting directories ...')
 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(' To upload :' + remoteIndex)
   try:
    sftp.put(currentIndex, remoteIndex)
    try:
     sftp.file(remoteIndex)
     sftp.chmod(remoteIndex, int("775", 8))
     print(' Modify the ' + remoteIndex + ' Permissions for 755')
     print(fullpathitem + ' Uploaded successfully ')
    except:
     print(fullpathitem + ' Upload failed ')
     continue
   except Exception as e:
    print(' The error message :' + str(e))
    continue
  

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

Finished with code Show, start explaining 1 wave in detail

This method is to detect any Index. Under my current directory php this file, if not directly quit don't proceed to the next step 1, there is a small pit, is you Index. php the filename, you write lowercase index. php, can also True, here there is a place to pay attention to, is to changes the value of the currentIndex must add global in front, or null otherwise


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 server ...')

This is to connect to the server and create SFTP, using Try to catch the exception error


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

sftp.chdir is used to switch directories, equivalent to cd /www/wwwroot of the shell command
sftp. listdir(path='.') is to return the folder under the current directory, and return in the form of an array, and then put it into a full path and save it in the local array for later use, here is an if in is used to skip 1 site directory, such as I xxx. demo. com this directory do not want to update, just write in the beginning of SkipArry, used to skip


def getDirectory(sftp):
 print(' Start getting directories ...')
 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 part of uploading. First, traverse out the folder directory we need to modify, then concatenate the file Index.php to form the file path of remote server, and then use sftp.put function to upload our file. The first parameter is the path of the local file. Second parameter is the path of the remote server, after the success of the upload. Use sftp file to verify if the file exists, but I'm here to do a backup processing (a little bug temporarily commented out) first, first the original Index. php BackIndex. The name was changed to upload new Index php in. php, this function is useful, or I write not do so, because no upload success will certainly exists a Index. php file. After uploading, use sftp. chmod method to change the permissions of the file to 755. There is a pit here, you can directly write 755 in the second parameter, and you will find that the generated file permissions are 363.


def uploadIndex(sftp):
 for fullpathitem in fullpathArry:
   remoteIndex = fullpathitem + '/Index.php'
   print(' To upload :' + remoteIndex)
   try:
    sftp.put(currentIndex, remoteIndex)
    try:
     sftp.file(remoteIndex)
     sftp.chmod(remoteIndex, int("775", 8))
     print(' Modify the ' + remoteIndex + ' Permissions for 755')
     print(fullpathitem + ' Uploaded successfully ')
    except:
     print(fullpathitem + ' Upload failed ')
     continue
   except Exception as e:
    print(' The error message :' + str(e))
    continue

Then execute it one by one in main, then all the files under the corresponding directory on the server can be replaced with my local files. The code is not much, but the effect is good. Indeed, life is short, I use Python

conclusion


Related articles: