利用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实现计算最小编辑距离
Mar 17 Python
python使用pymysql实现操作mysql
Sep 13 Python
python爬取w3shcool的JQuery课程并且保存到本地
Apr 06 Python
python中将函数赋值给变量时需要注意的一些问题
Aug 18 Python
Python使用selenium实现网页用户名 密码 验证码自动登录功能
May 16 Python
Python图像处理之颜色的定义与使用分析
Jan 03 Python
python仿抖音表白神器
Apr 08 Python
python getpass模块用法及实例详解
Oct 07 Python
python实现QQ邮箱发送邮件
Mar 06 Python
Django多层嵌套ManyToMany字段ORM操作详解
May 19 Python
QML实现钟表效果
Jun 02 Python
Python提取PDF指定内容并生成新文件
Jun 09 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
解密ThinkPHP3.1.2版本之模块和操作映射
2014/06/19 PHP
php 猴子摘桃的算法
2017/06/20 PHP
PHP读取、解析eml文件及生成网页的方法示例
2017/09/04 PHP
php下的原生ajax请求用法实例分析
2020/02/28 PHP
JavaScript写的一个自定义弹出式对话框代码
2010/01/17 Javascript
javascript 解决表单仍然提交即使监听处理函数返回false
2010/03/14 Javascript
基于MooTools的很有创意的滚动条时钟动画
2010/11/14 Javascript
javascript匿名函数实例分析
2014/11/18 Javascript
jQuery实现设置、移除文本框默认值功能
2015/01/13 Javascript
介绍JavaScript中Math.abs()方法的使用
2015/06/14 Javascript
纯js代码实现未知宽高的元素在指定元素中垂直水平居中显示
2015/09/12 Javascript
javascript中Date对象应用之简易日历实现
2016/07/12 Javascript
浅谈javascript中的数据类型转换
2016/12/27 Javascript
JS+canvas动态绘制饼图的方法示例
2017/09/12 Javascript
Vue.js 父子组件通信的十种方式
2018/10/30 Javascript
js实现图片放大并跟随鼠标移动特效
2019/01/18 Javascript
微信小程序实现授权登录
2019/05/15 Javascript
微信小程序云开发实现云数据库读写权限
2019/05/17 Javascript
在vue+element ui框架里实现lodash的debounce防抖
2019/11/13 Javascript
Python制作爬虫抓取美女图
2016/01/20 Python
python中的split()函数和os.path.split()函数使用详解
2019/12/21 Python
Python的PIL库中getpixel方法的使用
2020/04/09 Python
解决python执行较大excel文件openpyxl慢问题
2020/05/15 Python
如何在python中实现线性回归
2020/08/10 Python
python如何绘制疫情图
2020/09/16 Python
Python3爬虫RedisDump的安装步骤
2021/02/20 Python
印度在线内衣和时尚目的地:Zivame
2017/09/28 全球购物
Johnson Fitness澳大利亚:高级健身器材
2021/03/16 全球购物
职业规划书如何设计?
2014/01/09 职场文书
25岁生日感言
2014/01/13 职场文书
给学校的建议书
2014/03/12 职场文书
期末考试复习计划
2015/01/19 职场文书
李强感恩观后感
2015/06/17 职场文书
2019个人半年工作总结
2019/06/21 职场文书
如何用JS实现简单的数据监听
2021/05/06 Javascript
nginx配置虚拟主机的详细步骤
2021/07/21 Servers