利用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中元类用法实例
Oct 10 Python
python结合API实现即时天气信息
Jan 19 Python
python发送邮件功能实现代码
Jul 15 Python
简单了解Django模板的使用
Dec 20 Python
运动检测ViBe算法python实现代码
Jan 09 Python
Python中的defaultdict与__missing__()使用介绍
Feb 03 Python
详解Python利用random生成一个列表内的随机数
Aug 21 Python
python 魔法函数实例及解析
Sep 25 Python
Python函数式编程指南:对生成器全面讲解
Nov 19 Python
Python线程障碍对象Barrier原理详解
Dec 02 Python
python实现低通滤波器代码
Feb 26 Python
python 在sql语句中使用%s,%d,%f说明
Jun 06 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循环获取GET和POST值的代码
2008/04/09 PHP
PHP 查找字符串常用函数介绍
2012/06/07 PHP
php生成excel列序号代码实例
2013/12/24 PHP
兼容IE和Firefox的javascript获取iframe文档内容的函数
2011/08/15 Javascript
jqTransform form表单美化插件使用方法
2012/07/05 Javascript
js获取客户端外网ip的简单实例
2013/11/21 Javascript
js给网页加上背景音乐及选择音效的方法
2015/03/03 Javascript
在JavaScript中使用对数Math.log()方法的教程
2015/06/15 Javascript
JS版元素周期表实现方法
2015/08/05 Javascript
JQuery元素快速查找与操作
2018/04/22 jQuery
React通过redux-persist持久化数据存储的方法示例
2019/02/14 Javascript
微信小程序实现的一键复制功能示例
2019/04/24 Javascript
微信小程序云开发修改云数据库中的数据方法
2019/05/18 Javascript
原生js+ajax分页组件
2020/01/30 Javascript
如何构建一个Vue插件并生成npm包
2020/10/26 Javascript
python实现类似ftp传输文件的网络程序示例
2014/04/08 Python
Python入门篇之列表和元组
2014/10/17 Python
基于Python实现的百度贴吧网络爬虫实例
2015/04/17 Python
在Python中操作字符串之startswith()方法的使用
2015/05/20 Python
Python生成数字图片代码分享
2017/10/31 Python
python列表list保留顺序去重的实例
2018/12/14 Python
详解python做UI界面的方法
2019/02/27 Python
Python datetime包函数简单介绍
2019/08/28 Python
Python 使用元类type创建类对象常见应用详解
2019/10/17 Python
python3爬取torrent种子链接实例
2020/01/16 Python
PyTorch加载预训练模型实例(pretrained)
2020/01/17 Python
css3实现一款模仿iphone样式的注册表单
2013/03/20 HTML / CSS
friso美素佳儿官方海外旗舰店:荷兰原产原罐
2017/07/03 全球购物
工程监理应届生求职信
2013/11/09 职场文书
监理资料员岗位职责
2014/01/03 职场文书
客服专员岗位职责
2014/02/28 职场文书
求职意向书范文
2014/04/01 职场文书
新学期红领巾广播稿
2014/10/04 职场文书
2014年医院个人工作总结
2014/12/09 职场文书
2015年调度员工作总结
2015/04/30 职场文书
人事行政部各岗位职责说明书!
2019/07/15 职场文书