国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-15 22:36:23
字體:
來源:轉載
供稿:網友

前言

買了個Linux服務器,Centos系統,裝了個寶塔搭建了10個網站,比如有時候要在某個文件上加點代碼,就要依次去10個文件改動,雖然寶塔是可視化頁面操作,不需要用命令,但是也麻煩,雖然還有git的hook方法,但是操作也麻煩,新建個目錄的話還得操作一次,所以萌生了一個想法,用Python來批量更新服務器上的文件

序言

在網上搜索了一圈,發現Python有個庫叫paramiko可以專門拿來干這個事,具體資料和安裝就網上去搜索吧,我就直接上代碼了,不到100行,其實還可以精簡吧,后面再說了,先把功能實現了再說,Show Code

代碼

import paramikoimport os# 連接信息host = 'xxx.65.9.191'port = 22username = '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('文件檢測成功,準備連接服務器...')            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邹城市| 承德市| 即墨市| 花垣县| 米脂县| 习水县| 德惠市| 冀州市| 紫阳县| 航空| 钦州市| 五常市| 阳山县| 固阳县| 深圳市| 桦川县| 淅川县| 通化市| 怀宁县| 大冶市| 华安县| 布尔津县| 彭阳县| 田林县| 台前县| 运城市| 柘荣县| 师宗县| 定州市| 内黄县| 资溪县| 廊坊市| 阿克陶县| 敖汉旗| 武清区| 明星| 永川市| 虞城县| 安化县| 高清| 炉霍县|