前言
買了個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('文件檢測成功,準備連接服務器...')
新聞熱點
疑難解答