2018-07-30 14:50:02 343浏览
今天扣丁学堂Python培训老师给大家介绍一下关于如何利用Python批量更新服务器文件的内容,比如同学们买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦,虽然还有git的hook方法,但是操作也麻烦,新建个目录的话还得操作一次,所以萌生了一个想法,用Python来批量更新服务器上的文件,下面我们一起来看一下吧。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()
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('目录获取完毕')
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
以上就是关于扣丁学堂Python开发如何利用Python批量更新服务器文件的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,扣丁学堂Python技术交流群:279521237。
【关注微信公众号获取更多学习资料】