利用Python如何批量更新服务器文件


Posted in Python onJuly 29, 2018

前言

买了个Linux服务器,Centos系统,装了个宝塔搭建了10个网站,比如有时候要在某个文件上加点代码,就要依次去10个文件改动,虽然宝塔是可视化页面操作,不需要用命令,但是也麻烦,虽然还有git的hook方法,但是操作也麻烦,新建个目录的话还得操作一次,所以萌生了一个想法,用Python来批量更新服务器上的文件

序言

在网上搜索了一圈,发现Python有个库叫paramiko可以专门拿来干这个事,具体资料和安装就网上去搜索吧,我就直接上代码了,不到100行,其实还可以精简吧,后面再说了,先把功能实现了再说,Show 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()

代码Show完了,开始详细解释一波

这个方法是检测我当前目录下有没有Index.php这个文件,如果没有的话就直接退出不进行下一步了,这里有个小坑,就是你Index.php这个文件名,你写小写的index.php,也能为True,这里有个要注意的地方,就是要修改currentIndex的值,必须在前面加上global,否则还是为空

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

这是连接服务器并创建SFTP,使用了Try来捕获异常错误

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))

这里就是执行操作命令了,使用sftp对象来操作,sftp.chdir是用于切换目录,相当于shell命令的cd /www/wwwroot
sftp.listdir(path='.')是返回当前目录下的文件夹,且是以数组形式返回,然后将其拼接成完整路径后再保存在本地数组里备用,这里有个if in是用来跳过一些网站目录,比如我xxx.demo.com这个目录不想更新,就在开头的SkipArry里写上,用来跳过

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.php形成远程服务器的文件路径,然后使用sftp.put函数来上传我们的文件,第一个参数是本地文件的路径,第二个参数是远程服务器上的路径,上传成功后使用sftp.file来验证该文件是否存在,其实这里我是做了个备份处理的(有点bug就暂时先注释掉了),先将原本的Index.php改名为BackIndex.php在上传新的Index.php,这个判断函数才有用,不然我这样写没啥用,因为上没上传成功肯定都会存在一个Index.php文件.上传好了之后使用sftp.chmod方法来改变该文件的权限为755,这里有个坑,你直接在第二个参数写755,会发现生成的文件权限为363,经过多次试验发现,第二个参数要传入8进制的755,也就是493,生成的权限就是755了,感觉有点坑爹。

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

然后在main里依次执行,就能将服务器上对应的目录下的文件全部替换成我本地的文件了,代码不多,但效果好使啊,果然是人生苦短,我用Python

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
新手该如何学python怎么学好python?
Oct 07 Python
Python实现保证只能运行一个脚本实例
Jun 24 Python
python获取元素在数组中索引号的方法
Jul 15 Python
Python基础篇之初识Python必看攻略
Jun 23 Python
Python序列循环移位的3种方法推荐
Apr 09 Python
对Python中实现两个数的值交换的集中方法详解
Jan 11 Python
Python爬虫实战之12306抢票开源
Jan 24 Python
python按修改时间顺序排列文件的实例代码
Jul 25 Python
Python 离线工作环境搭建的方法步骤
Jul 29 Python
TensorFlow基于MNIST数据集实现车牌识别(初步演示版)
Aug 05 Python
python实现根据文件格式分类
Oct 31 Python
python编程学习使用管道Pipe编写优化代码
Nov 20 Python
python高阶爬虫实战分析
Jul 29 #Python
python3.5基于TCP实现文件传输
Mar 20 #Python
python3基于TCP实现CS架构文件传输
Jul 28 #Python
python cs架构实现简单文件传输
Mar 20 #Python
Tornado Web Server框架编写简易Python服务器
Jul 28 #Python
python使用tornado实现登录和登出
Jul 28 #Python
基于python实现简单日历
Jul 28 #Python
You might like
深入php self与$this的详解
2013/06/08 PHP
jquery+thinkphp实现跨域抓取数据的方法
2016/10/15 PHP
Javascript的常规数组和关联数组对比小结
2012/05/24 Javascript
简洁Ajax函数处理(示例代码)
2013/11/15 Javascript
使用JS或jQuery模拟鼠标点击a标签事件代码
2014/03/10 Javascript
js库Modernizr的介绍和使用
2015/05/07 Javascript
jQuery继承extend用法详解
2016/10/10 Javascript
Bootstrap优化站点资源、响应式图片、传送带使用详解3
2016/10/14 Javascript
web前端开发upload上传头像js示例代码
2016/10/22 Javascript
基于vuejs+webpack的日期选择插件
2020/05/21 Javascript
JS前端开发判断是否是手机端并跳转操作(小结)
2017/02/05 Javascript
JavaScript实现一个空中避难的小游戏
2017/06/06 Javascript
详解express与koa中间件模式对比
2017/08/07 Javascript
JavaScript实现仿Clock ISO时钟
2018/06/29 Javascript
js实现树形数据转成扁平数据的方法示例
2020/02/27 Javascript
vue实现数字滚动效果
2020/06/29 Javascript
解决vue-router路由拦截造成死循环问题
2020/08/05 Javascript
Ubuntu 16.04 LTS中源码安装Python 3.6.0的方法教程
2016/12/27 Python
python3利用Dlib19.7实现人脸68个特征点标定
2018/02/26 Python
python时间日期函数与利用pandas进行时间序列处理详解
2018/03/13 Python
更换Django默认的模板引擎为jinja2的实现方法
2018/05/28 Python
python实现三次样条插值
2018/12/17 Python
详解python多线程之间的同步(一)
2019/04/03 Python
python3 反射的四种基本方法解析
2019/08/26 Python
PyTorch: Softmax多分类实战操作
2020/07/07 Python
实现CSS3中的border-radius(边框圆角)示例代码
2013/07/19 HTML / CSS
荷兰最大的鞋子、服装和运动折扣店:Bristol
2021/01/07 全球购物
给儿子的表扬信
2014/01/15 职场文书
酒店总经理助理岗位职责
2014/02/01 职场文书
节水口号标语
2014/06/19 职场文书
调研座谈会发言材料
2014/08/23 职场文书
科学发展观演讲稿
2014/09/11 职场文书
讲文明懂礼貌演讲稿
2014/09/11 职场文书
《草船借箭》教学反思
2016/02/23 职场文书
只需要这一行代码就能让python计算速度提高十倍
2021/05/24 Python
mysql 获取时间方式
2022/03/20 MySQL